Search code examples
regex.htaccess

RewriteRule using Negative Lookahead results in Server Error


I have the following htaccess rule which uses Negative Lookahead

RewriteRule ^(.*)\/(?!.*(contact|about|subscribe)).*$ /$1/?section=other

The url result expected is domain.com/dir/?section=other when the request is other than dir/contact etc. When the file is placed on the server, the result is Internal Server Error.

Here it at regex101

Any help on this would be much appreciated. I'm as clueless as a school bus on Sunday on this one.


Solution

  • When the file is placed on the server, the result is Internal Server Error

    You are getting 500 (Internal Server Error) because your rule is running into loop as regex pattern keeps matching rewritten URL also which is /dir/.

    You may use this rule to fix this:

    RewriteRule ^([^/]+)/(?!.*(contact|about|subscribe|favorite)).+$ $1/?section=other [QSA,L,NC]
    

    Note use of .+ after / to prevent it to match just /dir/.

    Updated RegEx Demo