【问题标题】:htaccess - subdirectory as root, force https, non-wwwhtaccess - 作为根目录的子目录,强制 https,非 www
【发布时间】:2016-07-05 22:46:06
【问题描述】:

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

  1. 强制 https
  2. 强制非www
  3. 有一个子目录/live 成为域根

服务器是这样的:

/
/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

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

谢谢

【问题讨论】:

    标签: .htaccess redirect https rewrite subdirectory


    【解决方案1】:

    您可以使用以下代码:

    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]
    

    上面的代码会先重定向:

    然后重写

    【讨论】:

      【解决方案2】:

      颠倒你的规则的顺序,简化一些小事情:

      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]
      

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

      【讨论】:

      • 这很好用,但我注意到它不包含 /live 中的任何内容。例如 example.com/subdirectory 最终显示 example.com/live/subdirectory。虽然如果我包含一个斜杠example.com/subdirectory/,它将保持不变。有什么建议为什么会这样,或者在没有斜杠的情况下如何避免这种情况?
      • 尝试了清除缓存。如果我请求example.com/subdirectory,地址中仍然显示example.com/live/subdirectory/
      • 这是可行的,但现在相对路径已损坏。所以example.com/subdirectory 不添加尾部斜杠并且图像/资产路径不起作用。但是example.com/subdirectory/ 效果很好。
      • 所有路径现在都在工作。你最后的调整就是最终的答案。感谢您的宝贵时间。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 2014-02-20
      • 2016-10-02
      • 1970-01-01
      • 2012-06-01
      • 2023-03-03
      相关资源
      最近更新 更多