htaccess rewrite directory url to file.html

3

Hi, I'm trying to redirect and / or rewrite a set of URLs.

Example:

misitio.com/categoria1 --> misitio.com/categoria1.html

For now I have this, which correctly rewrites this first level:

RewriteRule ^categoria1/(\w+)$ $1.html [QSA,L]

However, I can not find the conditional regular expression if there were more nested categories and I had to take the last one as a model for the exit URL.

Example:

misitio.com/categoria1/categoria2/categoria3 --> misitio.com/categoria3.html

Or

Example:

misitio.com/categoria1/categoria2/categoria3/categoria4/categoria5/ --> misitio.com/categoria5.html

Can someone give me a cable? Thanks!

    
asked by RodoR 30.01.2016 в 21:52
source

1 answer

3

You could use something like this:

RewriteEngine On
RewriteRule ([^/]+)/?$ $1.html [NC,L]

This rule takes the last directory of the URL and redirects to the file of the same name (ending in .html). Note: the rule covers any word and not just the string "categoryXYZ", I hope that's fine.

The good: it is generic and with a rule you cover all cases. The bad: the URL must end with "/" or the redirect will not be done. Thanks to the Mariano's contribution , the code now makes the" / "optional.

    
answered by 31.01.2016 / 07:34
source