我正在寻找一些帮助来找到最兼容的,更重要的是强制非www.
和强制https的正确方法
www.
(这些规则用于添加www。所以需要微调)http://httpd.apache.org/docs/current/rewrite/remapping.html#canonicalhost
对于在80以外的端口上运行的站点:
RewriteCond "%{HTTP_HOST}" "!^www\.example\.com" [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteCond "%{SERVER_PORT}" "!^80$"
RewriteRule "^/?(.*) "http://www.example.com:%{SERVER_PORT}/$1" [L,R,NE]
对于在端口80上运行的站点
RewriteCond "%{HTTP_HOST}" "!^www\.example\.com" [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule "^/?(.*)" "http://www.example.com/$1" [L,R,NE]
如果您想对所有域名一般这样做 - 也就是说,如果您想将example.com的所有可能值重定向到www.example.com,您可以使用以下方法:
RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule "^/?(.*)" "http://www.%{HTTP_HOST}/$1" [L,R,NE]
http://wiki.apache.org/httpd/RewriteHTTPToHTTPS
RewriteEngine On
# This will enable the Rewrite capabilities
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e. http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context
只搜索Stackoverflow有数百个不同的例子,都有不同的样式,都有各种正则规则,都有各种选项,有些合并,有些没合并...
例如下面的一些不同的内容:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80 [OR]
RewriteCond %{HTTP_HOST} ^www.examplewebsite.com
RewriteRule ^(.*)$ https://examplewebsite.com/$1 [L,R=301]
或
RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^examplewebsite\.com$ [NC]
RewriteRule ^ https://examplewebsite.com%{REQUEST_URI} [R=301,L]
或
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} ^www*\.(.*examplewebsite\.com)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
或
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www*\.(.*examplewebsite\.com)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
目前我正在使用:
<IfModule mod_rewrite.c>
# Force HTTPS & NON-WWW
RewriteEngine On
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^examplewebsite\.com$ [NC]
RewriteRule ^ https://examplewebsite.com%{REQUEST_URI} [R=301,L]
</IfModule>
通过:https://github.com/h5bp/server-configs-apache/issues/48
找到但我想知道:
我还需要第二条规则,即为子文件夹中的.htaccess文件删除www。
目前我正在使用:
<IfModule mod_rewrite.c>
# Force Removal of WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]
</IfModule>
我认为这个稍好一点:
<IfModule mod_rewrite.c>
# Force Removal of WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%2://%1%{REQUEST_URI} [L,R=301]
</IfModule>
它非常有活力但是像上面一样,可以进行任何改进吗?有更好的规则吗,apache的规则更好吗?