I am trying to redirect all invalid urls to my index.php
file via my .htaccess file.
Unfortunately I keep getting an Apache error.
My .htaccess file
RewriteEngine on
RewriteCond %{REQUEST_URI} !.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^([a-zA-Z0-9-_/]*)$ index.php?p=$1
RewriteRule ^([A-Za-z0-9s]+)$ index.php?p=$1 [L]
This invalid url shoud redirect to index.php:
/vacatures/jobapplication/facility-manager%20qsdf
But it throws the object not found 404 Apache error.
2
Answers
The rule you have which allows spaces does not allow hyphens. The rule you have which allows hyphens does not allow spaces. So anything which includes both will not match either.
Your invalid URL
facility-manager%20qsdf
includes both.My guess is that your
RewriteCond
is supposed to apply to both rules, but that is not what is happening now, it will apply only to the firstRewriteRule
after it. You can solve all these problems by including just 1RewriteRule
, and amending it to accept everything you want:Note that this requires at least one of the characters in your character class, in other words it will not match your “home” location when there is no path (“http://somewhere.com/“). If you want to also match for that location, change the
+
to a*
, to allow 0 or more character matches.Your rewrite rules do not match the url you indicated. Your REQUEST_URI is
I suspect the URL decoding is not done before the RewriteRule matching and therefore it’s trying to match literally
%20
, yet%
sign is not included in your match. I’m not sure why you’re using twoRewriteRule
s – why not do something like this?