如何使用htaccess只重写某些页面

时间:2015-02-21 03:58:13

标签: php apache .htaccess mod-rewrite

我有一个小网站我想用htaccess重写一些页面并隐藏index.php。我正在试用这段代码:

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS_HOST} !^$
RewriteCond %{HTTPS_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ https%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteRule    ^despre-noi/?$    despre-noi.php    [R=301,NC,L]    # Handle requests for "despre-noi"
RewriteRule    ^detalii-plati/?$    cum-platesc.php    [R=301,NC,L]    # Handle requests for "modalitati de plata"
RewriteRule    ^contact/?$    contact.php    [R=301,NC,L]    # Handle requests for "contact"
RewriteRule    ^politica-de-confidentialitate/?$    politica-de-confidentialitate.php    [R=301,NC,L]    # Handle requests for "politica de confidentialitate"
RewriteRule    ^termeni-si-conditii/?$    termeni-si-conditii.php    [R=301,NC,L]    # Handle requests for "termeni si conditii"


</ifModule>

页面加载正常,但仍然显示.php扩展名,但是如果我在浏览器中键入没有.php扩展名的URL没有扩展名。你能帮忙告诉我哪里出错吗?因为我只希望那些页面处于这种状态,而不是整个网站。

谢谢

//编辑:我有ssl,因为这是https的条件。

1 个答案:

答案 0 :(得分:1)

从所有[R=301]规则中删除.php,例如

RewriteRule    ^despre-noi/?$    despre-noi.php    [NC,L]

添加以前对所有php文件使用的稍微修改过的规则。

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(despre-noi|cum-platesc|contact)\.php [NC]
RewriteRule ^ /%1 [L,R=301]

这需要在你的htaccess中已有的.php文件规则之前。在(..|..)条件的%{THE_REQUEST}表达式中添加您希望以这种方式工作的所有php文件的名称。


  

domain.com/contact.php将其显示为domain.com/contact-us

是的,这是可能的,但由于名称现在不同,您必须从当前contact规则的%{THE_REQUEST}条目中删除(..|..)并添加单独的规则,如下所示( .php规则)

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /contact\.php [NC]
RewriteRule ^ /contact-us [L,R=301]

然后只需将现有的.php规则修改为

RewriteRule    ^contact-us/?$    contact.php    [NC,L]