Best way to redirect to non-www AND enforce SSL at the same time

时间:2017-03-02 23:45:46

标签: apache .htaccess ssl mod-rewrite https

I created a way to redirect www to non-www and to redirect any http to https. However, I'm wondering if there's a more elegant and efficient way to do this. Here's my code:

# Force SSL
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [L,R=301]

# Rewrite all http to https
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://{HTTP_HOST}.com/$1 [R=301,L]

1 个答案:

答案 0 :(得分:1)

您可以使用单个RewriteRule强制执行非www和https:

RewriteEngine on

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]

以上OR和AND条件的组合允许我们一次操作2种类型的请求1)http www,2)https www和规则总是将它们重定向到ssl非www版本。您可以使用R = 301替换R以使重定向永久化。