.htaccess无扩展url和301重定向循环

时间:2014-02-24 23:09:55

标签: apache .htaccess mod-rewrite redirect

我花了不少时间尝试开发一个好的.htaccess来为SEO目的提供无扩展的URL。几乎我看到的每个现代网站都有无扩展的URL,而且我想采用这种方法是一个相当新的网站。

我已经能够使用.htaccess成功将网站转换为无扩展名。例如:

example.com/page.php将成为URL

中的example.com/page1

但是,在执行301重定向时,位于相同位置的现有页面(例如contact.php页面)将执行LOOP。因此,举例来说,搜索引擎不认为/contact.php和/ contact是两个不同的页面,现有的索引/contact.php有301重定向到/ contact

然而,/ contact url在幕后从/contact.php中提取数据,而.htaccess知道这一点,然后想再次将301重定向应用到后台/contact.php到/ contact,从而导致循环。我无法弄清楚如何阻止它。

底线是我希望从/contact.php中的301重定向到/与URL中的/ contact联系,反映/contact.php物理文件的内容。

这是我的.htaccess,除了有301重定向的页面之外,效果很好。

我也对你在.htaccess中看到的任何其他问题感兴趣:)

.htaccess
    Options -MultiViews
    Options +FollowSymLinks
    RewriteEngine on
    RewriteBase /


    ## 301 Redirects
        # 301 Redirect 1
        RewriteCond %{QUERY_STRING}  ^$
        RewriteRule ^contact\.php$ /contact? [R=301,NE,NC,L]


    ## Exclude appropriate directories from rewrite rules  ^(blogsphere)
        RewriteRule ^(blogsphere) - [L]

    ## Unless directory, remove trailing slash
        # If requested URL ending with slash does not resolve to an existing directory
            RewriteCond %{REQUEST_FILENAME} !-d
        # Externally redirect to remove trailing slash
            RewriteRule ^(.+)/$ $1 [QSA,L]

    ## Redirect external .php requests to extensionless url
        # Any type of POST/GET should be a condition so that it doesnt rewrite without that data (end fileames in submissionscript)
            RewriteCond %{REQUEST_URI} !^/([a-z-]+)\-(submissionscript)(.*)$
        #Request has to end in .php
            RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
            RewriteRule ^(.+)\.php$ $1$2 [QSA,L]

    ## If it is not a directory then internal resolve request to end with .php for extensionless php urls (/page will internally resolve to /page.php)
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^((?!(\.|\.php)).)*$ $0.php [QSA,L]

1 个答案:

答案 0 :(得分:0)

有这样的话:

Options -MultiViews
Options +FollowSymLinks
RewriteEngine on
RewriteBase /

# skip blogsphere directory for rewrite
RewriteRule ^(blogsphere) - [L]

## Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ $1 [R=301,L]

# remove .php extension from URL - external redirect 
RewriteCond %{REQUEST_URI} !^/([a-z-]+)-(submissionscript)(.*)$
RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ %1 [R=301,L,NE]

# internally rewrite a file to file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]