htaccess URL rewrite space replacement

百般思念 提交于 2020-01-06 02:08:05

问题


EDIT NOTE: Modified code to Documentroot

I am doing rewrite rules for a client's website and I started with my own website's blog rewrite rules, as they kinda match the customer needs. Now that every rules are modified to the client needs, I'm glad it is working super fine. Here is the final look;

Options +FollowSymlinks
RewriteEngine on

# executes repeatedly as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S*\s.*)$" /$1-$2 [L,NE]

# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" /$1-$2 [L,R=302,NE]

#Rewrite des urls blog
RewriteRule fashion/blog/([a-zA-Z0-9\s]+)/([a-zA-Z0-9\s]+)-([0-9]+) fashion/blogpost.php?brand=$1&url=$2&id=$3

#Rewrite des urls brands
RewriteRule fashion/brand/([a-zA-Z0-9\s]+)-([0-9]+) fashion/brand.php?brand=$1&id=$2

#Rewrite des urls shop brands
RewriteRule fashion/shop/brands/([a-zA-Z0-9\s]+)-([0-9]+) fashion/shopbrand.php?brand=$1&id=$2

#Rewrite des urls shop category
RewriteRule fashion/shop/category/([a-zA-Z0-9\-]+)-([0-9]+) fashion/shopcategory.php?url=$1&id=$2

#Enlever l'extension
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.*)$ $1.php [L] 

ErrorDocument 404 http://localhost/fashion/404.php

#RewriteCond %{REQUEST_URI} !/maintenance.php$
#RewriteCond %{REMOTE_ADDR} !^24\.201\.45\.57
#RewriteRule $ /maintenance.php [R=302,L]

I wanted to avoid having spaces issues with blogpost titles or brand names, so I did some searches and added a \s in my rules. It works fine, as this replace spaces by %20, so now the blogpost titles containing spaces are now accessible but I would like spaces to turn into dashes - and I cannot get it right.

There are many articles available that speaks about turning spaces into dashes but after testing a couple of them, I found out I have difficulties matching them rules to my existing rules.

Any tips or explanations will be greatly appreciated !


回答1:


To convert space to - you can use these 2 rules just below RewriteEngine On line:

# executes repeatedly as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S*\s.*)$" /$1-$2 [L,NE]

# executes when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" /$1-$2 [L,R=302,NE]


来源:https://stackoverflow.com/questions/28095656/htaccess-url-rewrite-space-replacement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!