RewriteRule用于在URL中包含子域的博客帖子

时间:2017-06-14 13:36:51

标签: php wordpress apache .htaccess mod-rewrite

致力于编写重定向规则,但我对它们或语法不太熟悉。

基本上我有Wordpress网址如下所示:

https://example.com/blog/blog-title/garbagetext

我需要能够将这样的网址重定向到我们的404页面,我的第一次尝试是:

RewriteRule ^blog/(.`*)/(.`*)/$ https://www.example.com/404.php [R=301,L]

这很有效,但它也无法访问实际的博客帖子,并且还重定向了这样的网址:

example.com/blog/blog-title

有关如何使其正常工作的任何想法?

1 个答案:

答案 0 :(得分:0)

RewriteRule ^blog/(.`*)/(.`*)/$ https://www.example.com/404.php [R=301,L]
:  
example.com/blog/blog-title

The directive you posted could not redirect the example URL that you say is being erroneously redirected. So, either you have other directives (possibly in other .htaccess files, or the server config) or there is a conflict with existing directives, or you are seeing a cached response? If you've previously experimented with 301 redirects then these will have been cached aggressively by the browser. (It can be easier to test with 302 - temporary - redirects for this reason.)

Since you are using WordPress (which uses a front controller) then any redirects should appear at the start of the file, before the front controller.

You also appear to have an erroneous slash at the end of the RewriteRule pattern that will fail to match an intended URL of the form /blog/blog-title/garbagetext.

I'll ignore the backticks for now - I assume they are probably just a styling typo in your question?

I need to be able to redirect URLs like this to our 404 page

You shouldn't be redirecting to a 404 page. It should be served with an internal subrequest instead. If you redirect then you first send a 3xx response back to the client, the client then issues a second request for your 404.php page (exposing the URL) and then you have to make sure you are manually setting the appropriate 404 HTTP response header.

So, you need to define the appropriate ErrorDocument and R=404 the response.

The posts that need to be redirected to the 404 are any posts that have text following that trailing slash, so far example: example.com/blog/customer-reviews/asdfa.

Try the following instead, at the top of your .htaccess file:

ErrorDocument 404 /404.php

RewriteRule ^blog/.+/. - [R=404]

This will match /blog/customer-reviews/asdfa, but it won't match /blog/customer-reviews/ (or /blog/customer-reviews). The R=404 flag triggers an internal request to the defined error document. The L flag is not required when using a none 3xx code. When there is no substitution text (ie. no target URL) then specify a hyphen (-) instead.

And make sure you've cleared your browser cache.