.htaccess htaccess-替换url的一部分

.htaccess htaccess-替换url的一部分,.htaccess,url,mod-rewrite,.htaccess,Url,Mod Rewrite,我有一个网站,我希望替换URL的一部分,https://example.com/[此部分]/file.ext 将在站点上请求的URL示例: https://example.com/example-page/sw.js https://example.com/example-page/image.jpg https://example.com/some-other-page/sw.js https://example.com/some-other-page/file.pdf https://exa

我有一个网站,我希望替换URL的一部分,
https://example.com/[此部分]/file.ext

将在站点上请求的URL示例:

https://example.com/example-page/sw.js
https://example.com/example-page/image.jpg
https://example.com/some-other-page/sw.js
https://example.com/some-other-page/file.pdf
https://example.com/page-with-attitude-4/sw.js
https://example.com/page-with-attitude-4/info.txt
我想如何重写它们:

https://example.com/content/example-page/sw.js
https://example.com/example-page/image.jpg
https://example.com/content/some-other-page/sw.js
https://example.com/some-other-page/file.pdf
https://example.com/content/page-with-attitude-4/sw.js
https://example.com/page-with-attitude-4/info.txt
换句话说,如果只请求sw.js,则重写到其他URL。 到目前为止,我在htaccess中使用的是:

RewriteRule ^(.*)\/sw.js$ content/$1/sw.js [L]
我一直在使用它作为测试人员,测试结果很好,但当我在现场使用它时,它就不起作用了。有什么帮助吗?

成功了

RewriteRule ^([A-Za-z-]+)/sw\.js$ /places/$1/sw.js [L,QSA]

将以下代码放在主目录
.htaccess
文件中:

RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} sw\.js 

#the line above to match sw.js

RewriteCond %{THE_REQUEST} !content

# the line above to exclude any request including content from the following rule

RewriteRule ^(.*)$ content/$1 [R=302,L,NE]

#the line above to apply redirection for requests that passed previous conditions and redirect any request ended with sw.js 

RewriteRule ^content/(.*)$ /$1 [L,QSA]

#the last line is to make internal redirection for original path

测试后,如果可以,将
302
更改为
301
如果您想进行永久重定向

关键是,修改后的
重写规则
模式(即
([A-Za-z-]+)
)只匹配一个路径段,因此可以防止重写循环。(此处不需要
QSA
标志-默认情况下会附加查询字符串。)@MrWhite,找到了相同的结果。总是这些你每天都无法处理的事情会占用你在项目中的大部分时间:)在阅读regex文档后,经过几个小时的反复试验,得出了相同的结论。由于我使用webiste进行测试,并且没有显示错误,所以我认为我的第一条重写规则是正确的。现在我知道那个网站并不是很好。无论如何,谢谢你!因为我刚才用RewriteRule做的,所以我现在就保留它,但非常感谢!)