如何在以下情况下重写网址?

时间:2018-02-19 05:45:36

标签: php apache .htaccess

我在以下网址上有一个网页。

https://example.com/contact.php

现在我想配置URL重定向。如果用户打开包含完整URL的页面,则应自动从URL中删除.php。

https://example.com/contact.php ==> https://example.com/contact/

现在https://example.com/contact/网址应该从/contact.php加载内容。我正在尝试下面的.htaccess,但它失败了,重定向循环。

RewriteEngine on

RewriteRule ^contact$ contact.php  [NC,L]
RewriteCond %{REQUEST_URI} !^contact.php$
RewriteRule ^contact.php$ http://example.com/contact/  [R=301]

2 个答案:

答案 0 :(得分:1)

使用以下代码删除扩展

# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(one)/?$ /$1.php [L,NC]

答案 1 :(得分:0)

尝试以下方法:

# It redirects the contact.php to /contact/, so .php extension is removed
RewriteRule ^contact\.php$ /contact/ [L,R=301]

# It fetches contact.php when /contact/ is requested by the user
RewriteRule ^/contact/$ /contact.php [L,NC]