mod_rewrite - some requests being rewritten should produce a 404 but don't
I've been working on creating seo friendly urls for my site and have done this successfully with the 开发者_运维百科following rules:
RewriteEngine on
RewriteBase /
#redirect non www to www
RewriteCond %{HTTP_HOST} ^example.co.uk [NC]
RewriteRule ^(.*)$ http://www.example.co.uk/$1 [L,R=301]
# Redirect any request with page=var to /var/ format
RewriteCond %{QUERY_STRING} ^page=(.+[^/])$ [NC]
RewriteRule ^index\.cfm$ http://%{HTTP_HOST}/%1/? [R=301,L,NC]
# If not an existing file or directory rewrite any request
# to page var.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+[^/])/$ index.cfm?page=$1 [QSA,L]
My problem is that because of the last rule (I think), any root dir request is made into a friendly url such as /pagethatdoesntpointanywhere/
whether it points anywhere or not. Now I'd be happy with a 404 but it's not doing that it's just displaying the homepage.
I've also tried adding a blanket 404 rule:
# 404 files that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .+ /notfound.html [R=404,L,NC]
But that makes all of the friendly urls 404s as well.
Could someone explain where I am going wrong here please?
Use
ErrorDocument 404 /notfound.cfm
to display not found error page when Apache cannot find the file (replacenotfound.cfm
by your file).In
index.cfm
, if value ofpage
parameter is unknown (e.g.pagethatdoesntpointanywhere
), display 404 error page (use the same/similar code asnotfound.cfm
). It is the right place to do considering your rewrite rules and the fact that you checking which page to display here anyway. Lots of products/frameworks work in similar fashion (for example: WordPress).
Use both #1 and #2. Number #2 will work for 1-folder deep URLs (e.g /meow/
) while #1 will catch any other URLs (e.f. /meow/kitten/
or /meow/wuf/oink.css
).
精彩评论