将外部.php请求重定向到无扩展名 URL


Re-direct External .php requests to extension-less URL

我管理着几个曾经用ColdFusion编写但现在是用PHP编写的网站。 我的 HTACCESS 文件针对每个站点的目标如下:

  1. 始终将裸域解析为 www.domain.com
  2. 重定向任何外部 .CFM 文件到 .PHP,只要文件存在
  3. 服务所有人 .PHP 请求作为无扩展名 URL,带或不带查询字符串

在大多数情况下,我的HTACCESS规则有效。 我遇到的唯一问题是搜索引擎中的外部.php请求无法解析为无扩展名的 URL。 这是HTACCESS文件:

#Main Page
DirectoryIndex index.php
AddDefaultCharset OFF
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# Never Use the naked domain
RewriteCond %{HTTP_HOST} ^domain'.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
# Never Use the naked domain and Remove PHP extension
RewriteCond %{HTTP_HOST} !^www'.domain'.com$ [NC]
RedirectMatch 301 /([A-Za-z0-9_'-]+)'.cfm(('?.*)|())$ http://www.domain.com/$1$2
RewriteRule ^([A-Za-z0-9_'-]+)(('?.*)|())$ http://www.domain.com/$1.php$2 [L]
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [R=301,L]
# Resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}'.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

我正在处理的大多数网站都没有SSL或HTTPS请求。 正如我所提到的,除了解析对无扩展名URL的.php请求外,这些规则已经起作用。 此外,我的HTACCESS文件被放置在我的Web根目录中。 提前感谢任何帮助。

保持你的.htaccess像这样:

#Main Page
DirectoryIndex index.php
AddDefaultCharset OFF
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# Never Use the naked domain
RewriteCond %{HTTP_HOST} ^domain'.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301,NE]
# Never Use the naked domain and Remove PHP extension
RewriteCond %{THE_REQUEST} '.(php|cfm)['s?] [NC]
RewriteCond %{DOCUMENT_ROOT}/$1'.php -f [NC]
RewriteRule ^(.+?)'.(cfm|php)$ /$1 [R=301,L,NE]
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [R=301,L]
# Resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1'.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

这组指令:

# Never Use the naked domain and Remove PHP extension
RewriteCond %{HTTP_HOST} !^www'.domain'.com$ [NC]
RedirectMatch 301 /([A-Za-z0-9_'-]+)'.cfm(('?.*)|())$ http://www.domain.com/$1$2
RewriteRule ^([A-Za-z0-9_'-]+)(('?.*)|())$ http://www.domain.com/$1.php$2 [L]

有一些问题。重写条件不适用于RedirectMatch,它甚至不是mod_rewrite的一部分。它是mod_alias的一部分,并在请求处理管道的不同部分应用。它可能看起来像这样:

RewriteRule ^(.*)'.(cfm|php)$ /$1 [L,R=301] 

无需按条件 HTTP_HOST 进行筛选。