Replace space with dash (-) in url only

2019-08-29 12:33发布

问题:

Is it possible to change the space in the url to a dash (-) without changing it in the code?

The URL is used to identify the page, so it is not possible to just change the url because the page will not be found anymore so str_replace is not usable in this solution.

Using str_replace twice, once to change the space to dash and on the page-loader to change it back to spaces isn't going to work either, some pages already have a dash in the pagename :)

I was hoping this could be achived with htaccess but I have no idea how. Is it possible with htacces to show a different url in the browser then the actual url?

For example: www.example.com/pages/hello%20world should be visable as www.example.com/pages/hello-world but the GET variable should still be hello%20world.

This is my current .htaccess file

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{THE_REQUEST} \s/+home/httpd/vhosts/domain.nl/httpdocs/app/View/Products/([^%20]*)%20([^\s]*) [NC]
    RewriteRule ^/home/httpd/vhosts/domain.nl/httpdocs/app/View/Products/%1-%2 [L,NE,R]
    RewriteRule "^(/home/httpd/vhosts/domain.nl/httpdocs/app/View/Products/)/([^-]*)-+(.*)$" "/$1/$2 $3" [L,NE,NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

Example url to one of the products = http://www.example.nl/software/category/details/this%20is%20a%20product-name

回答1:

You can try something like this in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+path/([^%20]*)%20([^\s]*) [NC]
RewriteRule ^ /path/%1-%2 [L,NE,R]

RewriteRule "^(path)/([^-]*)-+(.*)$" "/$1/$2 $3" [L,NE,NC]