Search code examples
regexurlmod-rewrite

Regex to match url with and without slash


We have this regex in our .htaccess

RewriteRule ^([^\.]+)$ $1.html

It matchs urls like: https://example.com/lib to a file called lib.html

We need it to also match: https://example.com/lib/ to the same file

Thanks.

Tried:

RewriteRule ^([^\.]+)?/$ $1.html
RewriteRule ^([^\.]+[^/]*)$ $1.html

Solution

  • You can rewrite it as two separate rules to keep it simple:

    RewriteRule (?!.*\.html$)^(.+)\/$ $1.html [last]
    RewriteRule (?!.*\.html$)^(.+)$ $1.html [last]
    

    It'll first try to match an on a URL ending with / and if that fails it'll continue to the next rule. The negative lookahead, (?!.*\.html$), is there to not rewrite URLs already ending with .html.

    The [last] flag makes it stop processing more rules in case there's a match.

    If you prefer to combine both in one rule:

    RewriteRule (?!.*\.html$)^(.+?)\/?$ $1.html [last]