Saravana Prakash Saravana Prakash - 4 years ago 132
Apache Configuration Question

How to check is uri exists in rewritemap else goto 404 page?

My requirement is check if url exists in the rewrite map file. If not exists, it should show the custom 404 page with status code 404.

Originally this code served the purpose:

RewriteMap plp-map dbm:${http.server.install.base}/dynamicmaps/plp-map
RewriteCond %{REQUEST_URI} ^/en/home/categories/.*
RewriteRule ^(.*) ${plp-map:$1|/content/mysite/en_ca/home/errors/404.html} [PT,QSA]


It was loading custom 404 page for /invalid.html. But the status was 200. Next I elaborated the rule as goto ErrorDocument if not exists in map; else redirect. as below:

RewriteCond %{REQUEST_URI} ^/en/home/categories/.*
RewriteMap plp-map dbm:${http.server.install.base}/dynamicmaps/plp-map
RewriteCond ${plp-map:$1} =""
RewriteRule .? - [S=2]
RewriteCond %{REQUEST_URI} ^/en/home/categories/.*
RewriteRule ^(.*) ${plp-map:$1} [PT,QSA]
RewriteRule .? - [S=1]
RewriteRule ^(.*)$ - [L,R=404]
ErrorDocument 404 /content/homedepot_ca/en_ca/home/errors/404.html


Now this rule is failing at third line RewriteCond ${plp-map:$1} ="" with error

map lookup FAILED: map=plp-map[dbm] key=


Shouldn't the $1 always return the url? Somehow I am missing the part to pass url into condition checking map entry. How to fix this? Also is there a better solution for my issue?

Answer Source

No, $1 does not return the URL. It returns the result from the first group captured in your current RewriteRule regex.

Are you actually changing the URL with your map, or just testing it? If it's just a test, all you need is:

RewriteMap plp-map  dbm:${http.server.install.base}/dynamicmaps/plp-map
ErrorDocument 404 /content/homedepot_ca/en_ca/home/errors/404.html

RewriteCond ${plp-map:$1} =""
RewriteRule ^(/en/home/categories/.*)$ - [R=404,L]

If you're also changing it, add this after the above:

RewriteCond ${plp-map:$1} !=""
RewriteRule ^(/en/home/categories/.*)$ ${plp-map:$1} [PT,QSA]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download