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

How to use htaccess to rewrite only certain pages

我有一个小网站,我只想用 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?/ [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 的条件。

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

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 to show it domain.com/contact-us

是的,这是可能的,但由于现在名称不同,您必须从当前 %{THE_REQUEST} 规则的 (..|..) 条目中删除 contact 并添加一个单独的规则,如下所示 (再次在 .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]