繁体   English   中英

mod_rewrite将'_'替换为'-'

[英]mod_rewrite replace '_' with '-'

我几乎有一个mod_rewrite规则,但是我已经陷入了:)

我需要重写

country/[countryname].php 

country/[countryname]/

但是,[countryname]可能带有这样的下划线:'south_africa.php',如果确实如此,我想将其替换为连字符:'south-africa /'

我也想匹配该国家/地区后面是否有数字:“ france03.php”到“ france /”

这是我的规则,几乎在这里,但是即使下划线后没有第二部分,它仍然会添加连字符。

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

因此目前“ country / south_.php”变为“ country / south- /”

有人可以帮我找到拼图的缺失部分吗? 谢谢。

尝试这个:

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

此规则将使用单个下划线匹配url-您需要使用其他规则来获得更多的下划线,否则将没有。

如果要确保$2仅包含字母并且不为空,请将([^_]*?)更改为([a-zA-Z]+)

或者,您可以通过几遍操作来完成此操作:

# 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]

未经测试...不一定是“漂亮” :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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