【问题标题】:htaccess - replace part of urlhtaccess - 替换部分网址
【发布时间】:2017-09-26 17:58:19
【问题描述】:

我有一个网站,我想替换 URL 的一部分,https://example.com/[THISPART]/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]

我一直用http://htaccess.mwl.be/作为测试器,测试显示还可以,但是在现场使用时,它不起作用。有什么帮助吗?

【问题讨论】:

    标签: .htaccess url mod-rewrite


    【解决方案1】:

    将以下代码放在你的主目录.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

    【讨论】:

    • 因为我之前只使用了 RewriteRule,所以我暂时保留它,但非常感谢! :)
    【解决方案2】:

    成功了!

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

    【讨论】:

    • 至关重要的是,修改后的RewriteRule pattern(即([A-Za-z-]+))只匹配一个路径段,因此可以防止重写循环。 (此处不需要QSA 标志 - 默认情况下附加查询字符串。)
    • @MrWhite,发现了同样的情况。总是这些你每天不使用的东西在项目中占用最多的时间:) 在阅读了正则表达式文档后,经过几个小时的反复试验 - 得出了相同的结论。由于我使用该网站进行测试并且没有显示错误,我认为我的第一个重写规则是正确的。现在我知道那个网站并不是那么好。无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多