重定向到www,https并使用.htaccess

时间:2015-10-07 20:45:09

标签: regex apache .htaccess mod-rewrite redirect

这是我目前的.htaccess:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]

RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?p=$1

RewriteRule ^([a-zA-Z0-9_-]+)/(.*)$ index.php?p=$1&a=$2

它有效,但我想简化它以避免不必要的重定向。

我需要将用户重定向到WWW子域,HTTPS协议并根据需要添加尾部斜杠,并尽可能少地重定向。

有人可以建议一种方法来实现这个目标吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以将其缩小为:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^/?$ https://www.domain.com [R=301,L]

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

RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]

RewriteRule ^([\w-]+)/?$ index.php?p=$1 [L,QSA]    
RewriteRule ^([\w-]+)/(.+)$ index.php?p=$1&a=$2 [L,QSA]
相关问题