1

我有以下 .htaccess 工作完美:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [L]
RewriteRule ^(.*)$ http://www.mysite.com/mypage.php?u=$1 [NC]

这将允许我编写这样的网址:

http://www.mysite.com/peter  =>  http://www.mysite.com/mypage.php?u=peter

但是如果我想要一个额外的规则来避免为现有文件编写 .php 扩展名呢?

http://www.mysite.com/contact   (contact.php exists on file)

我尝试将此添加到我的 curr htaccess 中(但不起作用):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

换句话说,我想拥有虚荣网址并忽略同一 .htaccess 中的 .php 扩展名。


解决了!感谢 Ulrich Palha 和 Mario(不知道排序和 LAST [L] 标志!

RewriteEngine on
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://www.mysite.com/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://www.mysite.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [L]
RewriteRule ^(.*)$ http://www.mysite.com/mypage.php?u=$1 [NC]
4

2 回答 2

1

这是订购的问题。RewriteRules 按照它们在 .htaccess 中注明的顺序应用
查看您曾经想知道的关于 Mod_Rewrite 规则但不敢问的所有信息?

只需将您的新块添加为第一个重写语句,添加一个[LAST]标志,它应该可以工作。

此规则无条件有效(不受任何 RewriteCond 保护),因此应始终是所有 RewriteRules 的最后一个:

 RewriteRule ^(.*)$ ...

(并且所有前面的 RewriteRules 最好带有一个[L]标志。你有一些解决方法。)

于 2011-12-21T01:00:01.203 回答
0

对我来说,这段代码有效:

在“ /etc/apache2/sites-available/default ”或“ httpd.conf ”中

您必须(至少)在默认目录中有这些选项

...
    <Directory />
        ...
        Options FollowSymLinks
        AllowOverride All
        ...
    </Directory>
...

或在站点特定站点目录中

...
    <Directory "/var/www/my-site">
        ...
        Options FollowSymLinks
        AllowOverride All
        ...
    </Directory>
...

并在站点目录中创建或编辑“ .htacces ”(例如“/var/www/my-site/.htaccess”)并添加以下代码:

AddType application/x-httpd-php htm html php
AddHandler application/x-httpd-php .htm .html

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
于 2013-01-23T12:34:01.920 回答