htaccess动态重写,SSL,非WWW

时间:2013-11-14 00:00:03

标签: apache .htaccess mod-rewrite

我正在尝试使用.htaccess重写和重定向来完成一些任务,但我遇到的问题是将它们完美地放在一起。我想完成三件事 -

  1. 表格http://www.domain.com/directory/index.php?p=page的网址需要重写/重定向到http://www.domain.com/directory/page
  2. 任何非WWW请求都应重定向到www。版本
  3. 只有某些页面应该重定向并在https下提供,而其他所有页面都会被重定向(如果需要)并在http
  4. 下提供

    这是我目前的情况,即从上面处理1和2。 #3被证明是挑战:

    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    
    #Rewrite for dynamic subpages (/directory/index.php?sitepage=page)
    RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ $1/index.php?sitepage=$2 [L]
    
    #Root level pages remove php extension
    RewriteRule ^([a-zA-Z0-9_-]+)$ $1.php [L]   
    

    非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您需要确保重定向高于路由规则(最后2个):

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# All the pages that must be HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/(directory1/page1|directory1/page2|page3)
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

#Rewrite for dynamic subpages (/directory/index.php?sitepage=page)
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ $1/index.php?sitepage=$2 [L]

#Root level pages remove php extension
RewriteRule ^([a-zA-Z0-9_-]+)$ $1.php [L]