Find us on Facebook

LightBlog
Responsive Ads Here

Thứ Tư, 27 tháng 12, 2017

htaccess: Remove trailing slash from URL ending with .xml/ only

Question:

I need to remove trailing slash from URLs ending with .xml/ only .. For this purpose I've created a Rewrite Condition and Rule which is working perfectly fine for the test link http://website.com/test.xml/
The problem is when I place the rule in WordPress .htaccess file, it doesn't work at all! Seems like WordPress or YOAST Permalink structure is overriding the rule .. please help!
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} /(.*).xml/$
RewriteRule ^ /%1.xml [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Note:
Please note that this is not a physical file .. using rewrite rules to generate sitemap on the run! This is a wordpress page in fact!
add_rewrite_rule('([^/]*)-placeholder.xml','index.php?page_id=123&custom‌​-slug=$matches[1]','‌​top');

Answer:

RewriteRule ^ /%1.xml [L]
This should be an external redirect, not an internal rewrite. (Otherwise it won't look like it's doing anything, as the visible URL won't change.) So, you need the R (redirect) flag. For example:
 RewriteRule ^ /%1.xml [R,L]
This is a temporary (302) redirect. Change R to R=301 to make it a permanent (301) redirect - but only when you are sure it's working OK. (Since 301s are cached hard by the browser and can make testing problematic.)
However, you don't need the RewriteCond directive. This can be done in a single RewriteRule (it will also be more efficient to do so). This should also go before your existing internal rewrites and ideally before the # BEGIN WordPress block, as otherwise your customisation could be overridden in future updates.
So, all you need is (at the top of your file):
RewriteRule ^(.+)\.xml/$ /$1.xml [R,L]
Remember to escape literal dots in your regex.
UPDATE: And yes, that should be $1 (as a backreference to the RewriteRule pattern) as opposed to %1 (a backreference to the last matched CondPattern).


Không có nhận xét nào:

Đăng nhận xét