【问题标题】:htaccess file to redirect non-www and https requests, and rewrite URLshtaccess 文件重定向非 www 和 https 请求,并重写 URL
【发布时间】:2013-01-25 01:39:35
【问题描述】:

我正在尝试创建我的第一个 .htaccess 以进行 URL 重写和其他操作,但我浪费了两天时间搜索信息并试图使其正常工作,但没有成功。

我想要达到的目标如下:

1) 将所有非 www 网址重定向到 www 网址(这似乎是 seo 的最佳做法?)

domain.com   -->  www.domain.com

2) 将所有 https 请求重定向到 http 请求:

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

3) 将我的网址重写为对 SEO 友好,并最终去除地址末尾的任何尾随斜杠:

www.domain.com/abc    -->  www.domain.com/index.php?page=abc
www.domain.com/abc/   -->  www.domain.com/abc


到目前为止,我所拥有的是三个单独工作的 sn-ps:

# 1) This should be correct, I hope!
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


# 2) This seems to work 100% right
RewriteEngine On
RewriteCond %{HTTPS} =on
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R,L]


#3) Major issues here
RewriteEngine On
RewriteRule ^([^/\.]+)/?$ index.php?page=$1 [L]

这部分有效:它可以满足我的要求,但是当我在 SEO 友好 URL 后面加上斜杠时,所有相对路径都被破坏了:

www.domain.com/abc      OK
www.domain.com/abc/     page gets displayed but all relative URL for css and images are broken


我什至不知道如何在单个 htaccess 文件中组合不同的规则以使它们正确交互。

对不起,解释太长了,这个问题让我很沮丧。

【问题讨论】:

    标签: apache .htaccess url redirect rewrite


    【解决方案1】:

    css 文件或图像的相对路径的问题当然在于尾部斜杠。浏览器认为他在子文件夹中,并将 css 文件的相对路径附加到您当前的位置,这将导致

    www.domain.com/abc/styles/style.css
    

    而不是

    www.domain.com/styles/style.css
    

    有两种方法可以解决这个问题:

    1. 我首选的解决方案是将 html 中的所有路径设为绝对路径。
    2. 重定向到相同的路径,不带斜杠。由于您似乎忽略了斜杠,因此这应该没有副作用。匹配规则如下所示

      RewriteRule ^([^/\.]+)/?$ http://%{HTTP_HOST}$1 [R=301,L]
      

    您的完整 htaccess 文件将是这个:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    
    RewriteCond %{HTTPS} =on
    RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R,L]
    
    RewriteRule ^([^/\.]+)/$ http://%{HTTP_HOST}$1 [R=301,L]
    RewriteRule ^([^/\.]+)$ index.php?page=$1 [L]
    

    【讨论】:

    • 感谢您的回复。 RewriteRule ^([^/\.]+)/$ http://%{HTTP_HOST}/$1 [R=301,L] 这里缺少一个斜线,但这是一个简单的修复。不幸的是,如果我输入 https://domain.com/abc/ 之类的内容,则不会发生 https 重定向
    • 对不起,我的错。这是我的虚拟服务器的愚蠢配置错误。它工作 100% 完美,非常感谢,现在这些 htaccess 文件对我来说似乎更容易理解!再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2011-01-02
    • 2015-04-20
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2014-07-26
    相关资源
    最近更新 更多