【问题标题】:.htaccess - rewrite nonwww to www; php to html; http to https.htaccess - 将非 www 重写为 www; php转html; http 转 https
【发布时间】:2014-03-22 20:52:46
【问题描述】:

我从几个小时以来一直在尝试关注: - .www 请求应重写为非 www - php应该被重写为html - http 应该重写为 https - 所有重定向代码为 301

我正在使用以下 .htaccess 文件:

RewriteEngine on

# www to non www
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com [NC]
RewriteRule (.*) http://mydomain.com/$1 [R=301] 

# php to html
RewriteRule ^(.*).html$ $1.php 
RewriteCond %{THE_REQUEST} \ /(.+)\.php
RewriteRule ^ /%1.html [R=301]


# http to https
RewriteCond %{SERVER_PORT} !^443$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301]

但它不会工作。如果我删除 http 到 https 规则,我会得到以下结果:

带有 .html 的 www 重定向到末尾带有 .php 的非 www:

 :~$ curl -I http://www.mydomain.com/index.html
 Location: http://mydomain.com/index.**php**

带有 .php 的 www 重定向到末尾带有 .html 的 www:

 :~$ curl -I http://www.mydomain.com/index.php
 Location: http://**www.**mydomain.com/index.html

非 www 与 php 作品,它被重定向到 html,这是正确的:

 :~$ curl -I http://mydomain.com/index.php
 Location: http://mydomain.com/index.html

并且使用 http 到 https 规则一切都搞砸了,因为域被双重插入:

 :~$ curl -I http://mydomain.com:81/index.php
 Location: https://mydomain.com:81/http://mydomain.com:81/index.html

我了解 http 到 https 重写的问题,因为它已经被重写,所以 url 被双重插入。但是解决这个问题的正确 htaccess 规则是什么?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    你可以试试这个。如果我清楚您想要什么,我相信这将满足您的要求。

    # www to non www and HTTPS if not
    RewriteCond %{HTTP_HOST} ^www\.mydomain\.com [NC,OR]
    RewriteCond %{HTTPS} !^on
    RewriteRule (.*) https://mydomain.com/$1 [R=301,L]
    
    #rewrite files to html
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)\.html$ /$1.php [L]
    

    【讨论】:

    • 你好,太棒了,curl 会返回正确的 URL。但我收到 404 错误。我认为这是因为我已将文件保存为 php,您也有解决方案吗? Edut:还有一件事:当我创建 curl mydomain.com/index.html 时,它会变为 mydomain.com/index.php,然后它会被重写为 mydomain.com/index.html。是否可以一步完成,所以没有两个 301 重定向?
    • 你想用 PHP 文件做什么? php 文件是真实文件吗?您只想将它​​们显示为 html?
    • 是的,这是真正的 php 文件。
    • 代码中是否链接了php文件?因为如果您希望它们显示为 .html,您应该在链接中使用 .html 并让 apache 在内部进行重定向,我可以更新代码来执行此操作。应该这样做。
    • 是的,有些php文件包含其他php文件并执行php代码。我可以更新我的 apache 配置,如果你能更新你的代码就好了。 HTTPS 重定向仍将通过 htaccess 进行,对吧?
    猜你喜欢
    • 2023-03-16
    • 2014-12-16
    • 2017-12-04
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多