mod_rewrite replace '_' with '-'

2019-07-18 09:01发布

问题:

I'm almost there with a mod_rewrite rule, but I've caved in :)

I need to rewrite

country/[countryname].php 

to

country/[countryname]/

however, [countryname] may have an underscore like this: 'south_africa.php' and if it does I want to replace it with a hypen: 'south-africa/'

I also want to match if the country has numbers following it: 'france03.php' to 'france/'

Heres my rule, its almost there but its still adding a hyphen even if there is no second part after the underscore.

RewriteRule ^country/(.*)_(.*?)[0-9]*\.php$ country/$1-$2 [R=301,L]

so currently 'country/south_.php' becomes 'country/south-/'

Can someone please help me find the missing piece of the puzzle? Thanks.

回答1:

Try this:

RewriteRule ^country/([^_]*)_([^_]*?)\d*\.php$ country/$1-$2 [R=301,L]

This rule will match urls with a single underscore - you'll need a different rule for more underscores or none.

If you want to make sure $2 contains only letter and isn't empty, change ([^_]*?) it to ([a-zA-Z]+).



回答2:

Alternatively you could do it over several passes:

# If request is for something in "country/"
RewriteCond %{REQUEST_URI} ^country/.+\.php$

# Replace underscore and digits with (single) hyphen
RewriteRule [_0-9]+ \-

# Remove extension (and possible trailing hyphen)
RewriteRule ^(.*)-?\.php$ $1

# Final rewrite
RewriteRule ^country/(.*)$ country/$1 [R=301,L]

Untested ... and not necessarily "pretty" :)