简体   繁体   中英

How to redirect URLs with blank space in .htaccess?

When I use this URL that contains %20 I don't get expected response.

localhost/worldsindia/company-search.php?company=Orissa%20Electrical%20Industries

This is with .htaccess

localhost/worldsindia/search/Orissa%20Electrical%20Industries

It is my PHP code, When I use .htaccess I get wrong response but when I use normal URL I get the expected response.

if(isset($_GET['company'])){
    $ss = $_GET['company'];    

}
echo $ss;

This is my .htaccess file

RewriteEngine On

<ifModule mod_headers.c>
Header set Connection keep-alive 
</ifModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
#AddOutputFilterByType DEFLATE text/plain
#AddOutputFilterByType DEFLATE text/html
#AddOutputFilterByType DEFLATE text/xml
#AddOutputFilterByType DEFLATE text/css
#AddOutputFilterByType DEFLATE application/xml
#AddOutputFilterByType DEFLATE application/xhtml+xml
#AddOutputFilterByType DEFLATE application/rss+xml
#AddOutputFilterByType DEFLATE application/javascript
#AddOutputFilterByType DEFLATE application/x-javascript

RewriteCond %{REQUEST_FILENAME} !-f


RewriteRule ^([^\.]+)/?$ $0.php [NC,L]

RewriteRule ^search/([A-Za-z0-9-]+)  company-search.php?company=$1 [NC,L]

Output:-

  1. With .htaccess is Orissa.
  2. With normal URL(localhost/worldsindia/company-search.php?company=Orissa%20Electrical%20Industries) Orissa Electrical Industries

RegEx is the expression that helps .htaccess to read your URL and achieve what you want.

Look at your Regex Last line in .htaccess : ([A-Za-z0-9-]+) It means accepting ONLY alphabet And digits. NOT SPACE CHARACTER

Why it cause problem when it comes to %20 ? Because %20 means space in URL , You are searching "Orissa Electrical Industries" .

So you should accept space character too, How ?

With \\s , it means Space character in RegEx .

It will be like this :

RewriteRule ^search/([A-Za-z0-9-\s]+)  company-search.php?company=$1 [NC,L]

PS: You can check and play with Regex in this RegExr

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