.htaccess htaccess文件:用连字符替换空格+指向新网址的链接

gj3fmq9x  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(110)

我想用连字符替换URL中的任何空格
这是我的完整htaccess文件:

Options -MultiViews

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^archive/([^/]+)$ news?title=$1

问题是我的标题经常包含空格,因此它返回以下URL:

example.com/archive/this%20is%20a%20test

我要创建的URL:example.com/archive/this-is-a-test
我读到我可以包括一个“\”来删除任何空格,但我的尝试没有工作...
一个相关的问题:我如何从另一个网页链接到这个新的url?我不能使用下面的php,因为它只会返回带有“% 20”符号的url:

<a class="readmore" href="/archive/<?php echo $row['title'];?>
nbnkbykc

nbnkbykc1#

将以下内容放入htaccess文件:

RewriteEngine On

# remove spaces from start or after with + 
RewriteRule ^(.*/|)[\s+]+(.+)$ $1$2 [L]

# remove spaces from end or before with + 
RewriteRule ^(.+?)[\s+]+(/.*|)$ $1$2 [L]

# replace spaces by - in betweenwith +
RewriteRule ^([^\s+]*)(?:\s|+)+(.*)$ $1-$2 [L,R]

相关问题