问题
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