mod_rewrite 替换 '_'与'-'

发布于 2024-10-01 12:40:43 字数 534 浏览 0 评论 0原文

我几乎已经有了 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-/'

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

原谅过去的我 2024-10-08 12:40:43

试试这个:

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

此规则将匹配带有单下划线的网址 - 您需要使用不同的规则来获取更多下划线或没有下划线。

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

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]+).

扛起拖把扫天下 2024-10-08 12:40:43

或者,您可以通过多次传递来完成:

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

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

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" :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文