【问题标题】:htaccess conditional rewritehtaccess 条件重写
【发布时间】:2011-06-22 08:29:35
【问题描述】:

我正在摆弄 .htaccess 和 mod_rewrite。我的网站有两种类型的 URL,我想重写:

  • /index.php?nav=$2
  • /index.php?nav=41&intNewsId=$3 -- 41 是静态的,新闻导航总是 41

我想将它们重写为:

  • /pagename/id
  • /news/pagename/id

我已经编写了一段有效的代码,但是如果我添加最后一行,第二行将停止工作,我可以想象那是因为第三块中的条件也适用于第二块强>。但我不知道如何正确使用条件。 (两个块单独工作)

Options +FollowSymlinks
RewriteEngine on

# Reroute rules that end on / 
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$ /$1/$2/ [R] 

# Make the system understand pagename/96
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/$ /index.php?nav=$2 

# Make the system understand news/pagename/99
RewriteRule ^(.*)\/(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/$ /index.php?nav=41&intNewsId=$3

我尝试了所有我能想到的方法,但我对 htaccess 中的这种正则表达式类型的键入或条件块不太熟悉。

解决方案: 我修复了自己的代码,我只是去掉了第二个 $ 所以条件不会干扰最后一个

Options +FollowSymlinks
RewriteEngine on

# Reroute rules that end on / 
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$ /$1/$2/ [R] 

# Make the system understand pagename/96
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/ /index.php?nav=$2 

# Make the system understand news/pagename/99
RewriteRule ^(.*)\/(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/$ /index.php?nav=41&intNewsId=$3

感谢大家的回答!

【问题讨论】:

  • 为什么这被选为题外话?
  • 另外,请注意,您可以通过使用 (\d+) 来避免那些 [0-9] 构造的笨拙,它捕获任何一位或多位数字的块。
  • Aww 谢谢你。注意我的 ([0-9]|[1-9][0-9]|[1-9][0-9][0-9]) ,之前情况更糟:D

标签: apache .htaccess


【解决方案1】:

试试这个:

RewriteRule ^news/.+/([^/]*)$ /index.php?nav=41&intNewsId=$1 [L]
RewriteRule ^.+/([^/]*)$ /index.php?nav=$1 [L]

【讨论】:

  • 谢谢哥们。使用它我也得到了它的工作:D 学习的一天 ^^
  • @Hans Wassink:不客气!如果我的回答解决了您的问题,请考虑通过单击我的回答左侧投票数下方的勾号来接受它。
【解决方案2】:

另一种方法,也许更简洁一些:

RewriteRule ^pagename/(\d+)$ index.php?nav=$1
RewriteRule ^news/pagename/(\d+)$ index.php?nav=41&intNewsId=$1

【讨论】:

    【解决方案3】:

    试试这个:

    # Make the system understand pagename/96
    RewriteCond %{REQUEST_URI} ^/pagename/([0-9]*)
    RewriteRule .* /index.php?nav=%1
    
    # Make the system understand news/pagename/99
    RewriteCond %{REQUEST_URI} ^/news/pagename/([0-9]*)
    RewriteRule .* /index.php?nav=41&intNewsId=%1
    

    【讨论】:

    • 谢谢伙计,使用它有效(我将页面名称更改为多字符正则表达式检查)我也修复了我自己的代码工作,我只是剥离了第二个 $ 所以条件不会干扰最后一个
    • 作为记录,RewriteCond 语句可以用适当的RewriteRules 省略:)
    • @Hans Wassink 很高兴它成功了。按条件编写规则总是好的,这样效率更高。
    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2011-10-02
    • 2016-12-14
    相关资源
    最近更新 更多