【问题标题】:Rewriting URLs with Mod-Rewrite使用 Mod-Rewrite 重写 URL
【发布时间】:2010-10-04 20:58:51
【问题描述】:

我将如何重写:

http://localhost/profile.php?user=MaFi

到

http://localhost/user/MaFi

【问题讨论】:

  • 这个问题属于ServerFault
  • 标签不应用于迁移请求。这就是近距离投票的目的。
  • 我的两分钱:我认为 mod-rewrite 问题通常适用于 SO,因为它实际上只是正则表达式,并且通常与某种 MVC 设置密切相关。

标签: mod-rewrite


【解决方案1】:

如果你真的想将/profile.php?user=MaFi 重定向到/user/MaFi,试试这个规则:

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)user=([^&]+)(&+(.*))?$
RewriteRule ^profile\.php$ /user/%3?%1%5 [L,R=301]

但如果你真的想在内部将/user/MaFi 重写为/profile.php?user=MaFi,试试这个规则:

RewriteRule ^user/([^/]+)$ profile.php?user=$1 [L]

【讨论】:

    【解决方案2】:

    尝试这样的 RewriteRule:

    RewriteRule ^profile.php?user=(.*)$ /user/$1      [R=301,L]
    

    【讨论】:

    • 这不起作用,因为查询不是 URI 路径的 URI 部分。
    • 嗯...我认为这确实有效,但进一步的研究证明我错了。 @Mafioso - Gumbo 是正确的,这条规则不会给你预期的结果。你应该接受他的回答。在它未被接受之前我无法删除它。
    【解决方案3】:

    yoursite.com/MaFi ~ yoursite.com/profile.php?user=MaFi

    <a href='/MaFi'>MaFi</a>
    
    RewriteRule ^([^.]+)$ "/profile.php?user=$1" [L]
    

    或许……

    yoursite.com/profile.php?user=MaFi ~ yoursite.com/MaFi

    <a href='/profile.php?user=MaFi'>MaFi</a>
    
    RewriteCond %{QUERY_STRING} user=(.+)
    RewriteRule ^([^.]+)$ "/%1" [QSA]
    

    我不是 100% 了解这些,但希望它们能有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多