我正在尝试将 /example 重定向到 Apache httpd.conf 中的 example.html,但它不起作用

I'm trying to redirect /example to example.html in Apache's httpd.conf, but it doesn't work

这是我要在 httpd.conf 中应用的代码:

<VirtualHost *:80>
    ServerName www.test.com
    ServerAlias www.test.com

    DocumentRoot /home/test_com
    ErrorLog /home/logs/apache/www_test/www.test.com-error_log
    CustomLog /home/logs/apache/www_test/www.test.com.-access_log common env=!do_not_log

    # https redirect
    RewriteEngine On

    RewriteCond %{HTTP_HOST} www.test.com
    RewriteCond %{REQUEST_URI} /example
    RewriteRule . https://www.test.com/example.html [R=303,L]

    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}

    <Directory "/home/test_com/">
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

</VirtualHost>

应用代码并重新启动 apache 后,当我转到 /example 时,我收到 404 not found 响应。

当我根据需要在 (https://htaccess.madewithlove.be), the output is as https://www.test.com/example.html 测试 htaccess 时。我想知道问题是什么。

RewriteRule 的右边部分是目标文件,尝试更改:

RewriteCond %{REQUEST_URI} /example

收件人:

 RewriteCond %{REQUEST_URI} /example.html
RewriteCond %{HTTP_HOST} www.test.com
RewriteCond %{REQUEST_URI} /example
RewriteRule . https://www.test.com/example.html [R=303,L]

when I go to /example I get a 404 not found response.

不确定您的示例中是否遗漏了某些内容,但根据所写的规则,如果您请求 /example 它将导致重定向循环,因为它将不断重定向到 /example.html一次又一次。 (除非你实际上是通过 HTTPS 发出请求,在这种情况下指令根本不做任何事情,你确实会得到 404!)

这是因为第二个条件%{REQUEST_URI} /example也匹配目标URL/example.html。您需要使正则表达式更具体并仅匹配 /example,而不是任何仅包含 /example 的 URL。此检查也可以移至 RewriteRule 指令(不需要 条件 )。例如:

RewriteRule ^/example$ https://www.test.com/example.html [R=303,L]

检查 HTTP_HOST 的条件似乎没有必要,因为这些指令在 www.test.com 的 vHost 中,所以它不能是任何其他主机名?

但是,由于此规则位于端口 80 的 vHost 中,因此它仅适用于 HTTP 请求(不适用于 HTTPS)。如果您实际上是在请求 https://www.test.com/example(即 HTTPS),就像 MWL 工具的测试结果所暗示的那样,那么该指令将永远不会被处理,您确实会得到 404.


RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}

您的 HTTP 到 HTTPS 重定向缺少最后一部分,因此将所有内容都重定向到主页。 RewriteRule 指令应为:

RewriteRule (.*) https://%{HTTP_HOST} [R=301,L]

但是,如果您的所有指令都在 vHost:80 容器中,则重定向到 HTTPS 没有意义。

这条规则也比它需要的更复杂。因为你在 vHost:80 容器中,所以 HTTPS 总是 off - 检查是多余的。


ServerName www.test.com
ServerAlias www.test.com

如果您只有一个主机名,那么您不需要两个指令。在这种情况下只需要 ServerName


When I test htaccess at (https://htaccess.madewithlove.be)

您这里没有 .htaccess 文件。您直接在 vHost 容器中使用指令,这是一个不同的 context。这些指令在这里的行为略有不同。例如,RewriteRule 模式 .(一个点)在这里与在 .htaccess 中使用时有不同的结果。在 virtualhost 上下文中, 每个 请求都是成功的,而在 .htaccess 中,它对所有 除了 主页(这大概是这里的用意)

但是,MWL .htaccess 测试人员仅发出“单一”请求(或单次通过文件)。它不会像在真实服务器环境中那样“跟随”重定向或多次通过文件。所以它无法捕获 redirect/rewrite 循环 - 这是错误的常见原因。