2009-10-06 194 views
0

嗨,大家好,我正试图实现我前几天在这里提出的另一个问题的答案之一。你可以发现,原来问题在这里:Mod_rewrite clarification question. Only for dynamic urls?.htaccess规则冲突帮助

最有用的答案和一个我后如下模型的实现:

I'm guessing the answer meder gave is the one you're looking for but technically you can create a static map file to redirect a set of title strings to ids and it doesn't have to execute an external prg executable:

RewriteMap static-title-to-id txt:/tmp/title_to_id.txt 
    RewriteRule ^/health-and-fitness-tips/(.*)/ /health-and-fitness-tips/${static-title-to-id:$1}/ [L] 

with the contents of the /tmp/title_to_id.txt file something like this:

how-do-I-lose-10kg-in-12-weeks 999 
    some-other-title 988 
    and-another 983 

好足够的背景。我的.htaccess文件目前有以下内容:

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteBase/
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule . /index.php [L] 
</IfModule> 

它是一个典型的WordPress的固定链接定制。但是,当我尝试添加与上面所选答案中提供的规则类似的规则时,我收到了内部服务器错误。

这是我的.htaccess文件时,我得到了内部服务器错误:

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteBase/
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule . /index.php [L] 
RewriteMap static-title-to-id txt:/tmp/title_to_id.txt 
RewriteRule ^/health-and-fitness-tips/(.*)/ /health-and-fitness-tips/${static-title-to-id:$1}/ [L] 
</IfModule> 

我希望我的问题是简单的东西,就像一个规则的冲突。如果你能看到一个错误或者可以在这里提供一些指导,那将是非常感谢。

回答

1

有在你的代码四个错误:

  1. RewriteMap direction只能在server configuration or virtual host context使用。

  2. 在.htaccess文件中使用mod_rewrite时,mod_rewrites首先从URL路径中删除每个目录前缀,然后再测试规则并在应用规则后重新进行。在.htaccess位于根目录的情况下,路径前缀将被删除,即/。所以,你需要在没有前缀指定路径模式:

    RewriteRule ^health-and-fitness-tips/(.*)/ /health-and-fitness-tips/${static-title-to-id:$1}/ [L] 
    
  3. 您的规则的替代也将通过同样的规则进行匹配。那会导致无限循环。所以你需要改变模式或替换以避免这种情况。你的情况变着花样会更好,例如:

    RewriteRule ^health-and-fitness-tips/([a-zA-Z]+[a-zA-Z0-9]+|[a-zA-Z0-9]+[a-zA-Z]+)/ /health-and-fitness-tips/${static-title-to-id:$1}/ [L] 
    

    你还应该指定的URL路径的末尾:

    RewriteRule ^health-and-fitness-tips/([a-zA-Z]+[a-zA-Z0-9]+|[a-zA-Z0-9]+[a-zA-Z]+)/$ /health-and-fitness-tips/${static-title-to-id:$1}/ [L] 
    
  4. 正如我认为这些网址不能直接映射到现有的文件或目录,你的第一条规则会在你重写它们之前抓住它们。所以,你应该改变的是规则的顺序有包罗万象的一个前应用的特定规则:

    RewriteRule ^health-and-fitness-tips/([a-zA-Z]+[a-zA-Z0-9]+|[a-zA-Z0-9]+[a-zA-Z]+)/$ /health-and-fitness-tips/${static-title-to-id:$1}/ 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule . /index.php [L] 
    
+0

谢谢您的回答浓汤!使用RewriteMap,我只需要将它添加到httpd.conf文件中并且{static-title-to-id:$ 1}应该可以工作?或者我必须以某种方式调用httpd.conf文件? – 2009-10-06 16:39:17

+0

@ivannovak:不,只需将其添加到您的httpd.conf文件并重新启动Apache,因为httpd.conf文件在Apache启动时只能读取一次。 – Gumbo 2009-10-06 17:21:34

+0

@Gumbo:我的.txt映射文件是由php脚本生成的。每次添加新帖子时,我应该如何自动检测新的地图规则?或者这是另一个问题的食物? – 2009-10-06 17:41:04