简体   繁体   中英

.htaccess redirect urls with spaces

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-9\s]+)$ 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.

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 first RewriteRule after it . You can solve all these problems by including just 1 RewriteRule , and amending it to accept everything you want:

RewriteRule "^([A-Za-z0-9\-\_\/\s]+)$" index.php?p=$1 [L] 

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

/vacatures/jobapplication/facility-manager%20qsdf 

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 two RewriteRule s - why not do something like this?

RewriteEngine on
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteCond %{REQUEST_URI} !^index.php(\?.*)?$
RewriteRule ^(.*)$ index.php?p=$1 [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM