Marcel Marcel - 3 months ago 10
PHP Question

Remove part of url, but keep extension

All of my websites are generated in the following pattern:

http://www.example.com/category/xyz/article---12345.html


I want to use mod_rewrite to remove the part "---12345", where the three minuses are always there, but the amount of numbers varies from 3 to 7.
The html shoul stay there so that the urls look like that:

http://www.example.com/category/xyz/article.html


How can I achieve that?

Answer

The following rule assumes that the html file you are requesting doesn't exist and will redirect them to the new html file name. It will do this for any .html file and not just those called "article".

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} \.html$
RewriteCond %{REQUEST_URI} ---
RewriteRule ^(.*)---(.*)$ "/$1.html" [R=301]

Things to note: If the original .html file exists remove the first two RewriteCond rules. If you don't want the address bar to change then replace [R=301] with [L]