Kevin Smith
Kevin Smith

Reputation: 111

Exact match for 404 errors

The code below allows example.com/bed/ and example.com/table/ and returns 404 errors for all other URLs with this structure: example.com/$$$/

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/.*\/    
RewriteCond %{REQUEST_URI} !bed|table [NC]
RewriteRule ^(.*)$ - [L,R=404]

The problem is 404 errors doesn't work for these structures: example.com/$$$bed$$$/ and example.com/$$$table$$$/

So how can I change the code to allow only exact match but NOT partial match.

Upvotes: 1

Views: 32

Answers (1)

anubhava
anubhava

Reputation: 785108

So how can I change the code to allow only exact match but NOT partial match.

Use anchors in your regex pattern:

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/(bed|table)/?$ [NC]
RewriteRule / - [L,R=404]

Regex pattern !^/(bed|table)/?$ will match everything except /bed/ and /table/ (with trailing slash optional).

Also note that you take out one extra RewriteCond %{REQUEST_URI} ^/.*\/ because that can be taken care of in RewriteRule itself.

Upvotes: 1

Related Questions