.htaccess上的Double RewriteRule

时间:2018-11-17 11:59:53

标签: .htaccess

我做了一个PHP博客,我希望为自己的帖子提供友好的SEO网址,并且还从我的网址中删除.php扩展名。所以我这样编辑了htaccess文件:

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d [NC]
    RewriteCond %{REQUEST_FILENAME} !-f [NC]
    RewriteRule ^(.*)$ viewpost.php?id=$1 [N]

    #second condition and rule
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^\.]+)$ $1.php [NC,L]

所以我得到了友好的SEO帖子网址,但第二个条件不起作用。但是,当我将其用作第一个条件时,它就可以工作。我做错了什么?非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

将第一个规则保留为.php处理程序规则,但应按以下所述检查.php文件的存在:

RewriteEngine On

# if not a directory and file.php exists then rewrite file to file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# rewrite every non-file or non-directory to viewpost.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ viewpost.php?id=$1 [L,QSA]