htaccess - 以root用户身份的子目录,强制https,非www

时间:2016-03-19 01:50:57

标签: .htaccess redirect https rewrite subdirectory

以下重写规则在我独立使用时有效。但他们在一起忽略了改变根。我想:

  1. 强制https
  2. 强制非www
  3. 有一个子目录/live成为域根
  4. 服务器是这样的:

    /
    /dev
    /live
    

    htaccess是这样的:

    RewriteEngine On
    
    # Rewrite /live to root
    RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
    RewriteRule !^live/ /live%{REQUEST_URI}  [L]
    
    # Remove www + force https
    RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
    RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]
    

    这应该发生:

    http://example.com      -> https://example.com
    http://www.example.com  -> https://example.com
    https://www.example.com -> https://example.com
    

    但这种情况发生了:

    http://example.com      -> https://example.com/live
    http://www.example.com  -> https://example.com/live
    https://www.example.com -> https://example.com/live
    

    如果有人建议如何使用这两个规则,那就太棒了,我不想将我的网站内容移到我服务器上的根目录中。

    由于

2 个答案:

答案 0 :(得分:1)

颠倒规则的顺序并简化一些小事:

RewriteEngine On

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

# add a trailing slash to directories
RewriteCond %{DOCUMENT_ROOT}/live%{REQUEST_URI}/ -d
RewriteRule !/$ %{REQUEST_URI}/ [L,NE,R=301]

# Rewrite /live to root
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule !^live/ /live%{REQUEST_URI} [L,NC]

在测试此更改之前清除浏览器缓存。

答案 1 :(得分:0)

您可以使用以下代码:

RewriteEngine on
#1)--http and www => https non-www--#
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule ^ https://%1%{REQUEST_URI} [NC,NE,L]
#2)--rewrite root to /live--#
RewriteCond %{REQUEST_URI} !^/live
RewriteRule ^(.*)$ /live/$1 [NC,L]

上面的代码首先会重定向:

然后重写