【问题标题】:mod_rewrite rewriting basemod_rewrite 重写基础
【发布时间】:2012-01-11 10:06:22
【问题描述】:

我正在一个网站上工作,我想使用 mod_rewrite 来重写 URL,例如

www.example.com/index.php?p=MYPAGE --> www.example.com/MYPAGE www.example.com/index.php?p=user?u=MYUSER --> www.example.com/user/MYUSER www.example.com/index.php?p=group?g=MYGROUP --> www.example.com/group/MYGROUP

到目前为止,我已经添加了这些规则。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?p=$1
RewriteRule ^user/(.+)$ index.php?p=user&u=$1

但我遇到了问题。如果我访问 www.example.com/single-page 一切都很好。然后,如果我访问 www.example.com/user/SMTHING,我不会得到我想要的。我尝试使用 C 和 L 标志,但没有任何成功。

有什么想法吗?

谢谢

【问题讨论】:

  • 仅供参考:重写问题在 ServerFault 和 Stack Overflow 上均有效。

标签: php mod-rewrite apache2


【解决方案1】:

你会试试这个 可能有用。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/(.+)$ index.php?p=user&u=$1
RewriteRule ^(.+)$ index.php?p=$1

重写规则的顺序很重要。

【讨论】:

  • 交换最后两行会带来更多麻烦。现在网站无法加载一些css和js
  • 问题在于,如果您不将 [L]ast 标志应用于规则,则仍会评估所有后续规则,因此http://example.com/user/thisguy 之类的 URL 将被两个规则重写为某些内容喜欢http://example.com/index.php?p=index.php?p=user&u=thisguy
  • 你说得对,我查看了 mod_rewrite 文档以更好地理解 [L] 标志。谢谢
【解决方案2】:

你有三个问题。首先是您的条件仅适用于遵循它们的第一条规则,因此您仍将重写合法文件请求。此外,您需要使用 [L]ast 标志以及像这样重新排序规则。把它们放在一起:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)$ $1                               [L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+)$ $1                               [L]

RewriteRule ^user/(.+)$ index.php?p=user&u=$1       [L]
RewriteRule ^(.+)$ index.php?p=$1

【讨论】:

    【解决方案3】:

    试试这个,它会起作用的:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    RewriteRule ^([^\/]+)$ index.php?p=$1
    RewriteRule ^([^\/])([^\/]+)\/([^\.]+)$ index.php?p=$1$2&$1=$3
    

    【讨论】:

      【解决方案4】:

      没有答案可能看起来像我的,所以这里是:

      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^user/([a-zA-Z0-9-]+)$ /index.php?p=user&u=$1 [QSA,L]
      RewriteRule ^group/([a-zA-Z0-9-]+)$ /index.php?p=group&g=$1 [QSA,L]
      RewriteRule ^([a-zA-Z0-9-]+)$ /index.php?p=$1 [QSA,L]
      

      我很确定它可以工作(或非常接近您想要的)。 请告诉我它是否有效...

      顺便说一下,更好的东西怎么样:

      RewriteRule ^(user|group)/([a-zA-Z0-9-]+)$ /index.php?type=$1&val=$2 [QSA,L]
      

      所以在您的 GET 中,您将拥有“type=user”或“type=group”和“val=the value”。有点概括的东西。

      【讨论】:

      • 当然可以!我是 RewriteRules 的人!看看我是如何赢得声誉的 LOL!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 2010-12-15
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多