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

时间:2014-11-19 18:04:58

标签: php apache .htaccess mod-rewrite

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

  1. 始终将裸域解析为www.domain.com
  2. 将任何外部.CFM文件重定向到.PHP,只要文件存在
  3. 将所有.PHP请求作为无扩展名的URL提供,包含或不包含QUERY STRINGS
  4. 在大多数情况下,我的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请求。正如我所提到的,除了将.php请求解析为无扩展URL之外,这些规则都有效。此外,我的HTACCESS文件放在我的Web根目录中。提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

这套指令:

# 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条件进行过滤。

答案 1 :(得分:0)

保持你的.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]
相关问题