Jhonny MeloLavou
Jhonny MeloLavou

Reputation: 11

How can I create exceptions in .htaccess

I want to use friendly urls:

RewriteRule ^([A-Za-z0-9_-]+)/$ pages/$1.php [QSA,L]

But at the same time, I want /forum/folder to be excluded from that rule in the .htaccess file.

How can I do that?

Upvotes: 1

Views: 1158

Answers (1)

MrWhite
MrWhite

Reputation: 45829

RewriteRule ^([A-Za-z0-9_-]+)/$ pages/$1.php [QSA,L]

... I want /forum/folder to be excluded

Your RewriteRule pattern (ie. ^([A-Za-z0-9_-]+)/$) already excludes the URL-path /forum/folder, since the pattern does not permit a slash (directory separator) in the middle of the URL-path; only at end.

So, if /forum/folder is still being routed then something else is doing this. If there is an additional .htaccess in this subdirectory (assuming it's a physical directory) that uses mod_rewrite then you could encounter conflicts.


Otherwise, there are a few ways to make an exception:

#1 - Exclude All Files and Folders: If you specifically want to exclude all files and folders from being rewritten (assuming /forum/folder is a physical directory) then you can specifically check for this and only process the RewriteRule if the URL-path does not map to a file or directory. For example:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/$ pages/$1.php [L]

The QSA flag is not required here, since the query string from the request is appended by default. Only if you are specifying a query string in the substitution and you need to merge this with the query string on the request do you need this flag. And as Deadooshka mentioned in comments, \w is a short hand character for [A-Za-z0-9_], so this simplifies the regex a bit.


#2 - Exclude Rule: Use a rule at the start of your file that matches the path you want to exclude and simply stop processing. For example:

RewriteRule ^forum/folder - [L]

If the requested URL starts with /forum/folder then stop here and don't process further rules.


#3 - Negated Condition: Include a negated conditon (RewriteCond directive) in the rule itself. For example:

RewriteCond %{REQUEST_URI} !^/forum/folder
RewriteRule ^([\w-]+)/$ pages/$1.php [L]

This will only process the RewriteRule if the requested URL does not start with /forum/folder. The ! prefix on the CondPattern negates the regex.


#4 - Negative Lookahead in the RewriteRule pattern: If you only have one rule and one URL you want to exclude from this rule then you could use a negative lookahead in the RewriteRule pattern (regex). For example, to exclude the URL /forum in the above directive:

RewriteRule ^((?!forum)[\w-]+)/$ pages/$1.php [L]

The (?!forum) is the negative lookahead.

Upvotes: 2

Related Questions