Enforce www and trailing slash with mod_rewrite htaccess on a multi-domain site

元气小坏坏 提交于 2019-12-11 20:18:05

问题


My goal is to enforce www and a trailing slash on urls to achieve this, in a multi-domain environment:

http://mydomain.com/company -> http://www.mydomain.com/company/

The catch is that certain sub domains must be excluded from the www prefix, yet still enforce the trailing slash, such as:

http://m.mydomain.com/company -> http://m.mydomain.com/company/

The additional factor is that I need to maintain any sub domain to avoid multiple redirects. For example:

http://dev.mydomain.com/login -> http://dev.mydomain.com/login/

Multiple redirects would result in:

http://dev.mydomain.com/login -> http://mydomain.com/login/

This needs to be avoided to keep the user on the current dev or mobile site.

What I have so far:

# Convert http://mydomain.com/company -> http://www.mydomain.com/company/
# Enforce www and trailing slash
# If you have subdomains, you can add them to
# the list using the "|" (OR) regex operator
RewriteCond %{HTTP_HOST} !^(www|dev|m)\.
RewriteCond %{HTTPS}s ^on(s)|
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]

This works for a domain that is missing the www prefix and trailing slash and adds them both in 1 redirect.

# Convert http://mydomain.com/company/ -> http://www.mydomain.com/company/
# Enforce www
# If you have subdomains, you can add them to
# the list using the "|" (OR) regex operator
RewriteCond %{HTTP_HOST} !^(www|dev|m)\.
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This works if a trailing slash is present and adds the www prefix if it is missing.

What I cant figure out is a method of redirecting a user if a sub domain is present and the trailing slash is missing.

RewriteCond %{QUERY_STRING} ^$    [NC]
RewriteRule ^((.*/)?[^/\.]+)$ /$1/ [R=301,L]

This rule works to add a trailing slash, but it will redirect a sub domain back to the root domain.

Can you recommend a solution that combines these rules into as few options as possible, yet achieves my goals and avoids multiple redirects?


回答1:


For the RewriteRule directive, the pattern is matched against the file system path corresponding to the request. So either use a RewriteCond with a suitable variable, or use proper variables when building the replacement, to generate a URL instead of a path.

Have you tried

RewriteCond %{QUERY_STRING} ^$    [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^((.*/)?[^/\.]+)$ http%1://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]

That should be the formulation most in sync with your other two rules. You will have to add a condition to that, though.



来源:https://stackoverflow.com/questions/13866817/enforce-www-and-trailing-slash-with-mod-rewrite-htaccess-on-a-multi-domain-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!