【问题标题】:url masking via htaccess rewrite is not working通过 htaccess 重写的 url 屏蔽不起作用
【发布时间】:2019-04-02 03:56:14
【问题描述】:

不确定这是否是 Stackoverflow 的正确部分来问我的问题...

但这里是:

所以我在.htaccess 文件上使用以下内容:

RewriteEngine On
RewriteRule ^sale?$ /discount-page/

这样当人们访问example.com/sale 页面时,他们会看到来自example.com/discount-page/ 的内容

但是当我访问example.com/sale 时,它会显示 404 错误,指出 URL /discount-page 在此服务器上不可用...

为什么会这样?

这是我的整个 .htaccess 文件的样子:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

有人可以帮忙吗?

【问题讨论】:

    标签: wordpress .htaccess url mod-rewrite masking


    【解决方案1】:

    使用 WordPress 时,您不能简单地将 .htaccess 中的 URL 重写为 %postname%(真正的 URL),因为 WP 仍会查看 REQUEST_URI 以路由 URL。即使您将/sale 重写为/discount-page/(实际URL),WordPress 仍会看到/sale(请求的URL)——它在WP 中不存在;因此是 404。

    虽然不是您的意图,但您可以将其更改为外部重定向来解决此问题(这也避免了潜在的重复内容问题)。例如:

    RewriteRule ^sale$ /discount-page/ [R,L]
    

    (我删除了^sale?$ 中的?,因为这看起来确实是错误的。或者你真的想匹配/sale/sal?)

    或者,您可以尝试重写底层的“普通”永久链接。 IE。明确传递%post_id%。这与重写 %postname% 不同,因为 WP 不需要检查 REQUEST_URI 来路由 URL。例如:

    RewriteRule ^sale$ /index.php?p=123 [L]
    

    其中123 是您的discount-page%post_id%。通过直接重写index.php,您实际上绕过了 WP 的前端控制器。

    请注意,这必须.htaccess(又名前端控制器)中的标准 WordPress 指令之前进行。


    但是,我仍然觉得应该有一种更像 WordPress 的方式来做这件事,这就是为什么我最初建议在 WordPress Stack 上问这个问题。但是,如果您这样做,请不要提及“.htaccess”。您真正创建的是 URL 别名或类似的东西。例如:Have two different URLs show the homepage

    【讨论】:

    • 感谢您的回复。我试过 RewriteRule ^sale$ /index.php?p=123 [L] 但它没有用。我仍然在地址栏中看到 /sale 网址。另外,我仍然看到来自 /sale 而不是 /discount-page 的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2012-02-05
    • 2015-02-03
    • 2014-08-08
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多