【问题标题】:htaccess redirect site/subfolder to site/subfolder.phphtaccess 将站点/子文件夹重定向到 site/subfolder.php
【发布时间】:2013-04-03 21:04:47
【问题描述】:

我有以下 .htaccess 文件

#~ Turn on rewrite engine
RewriteEngine on

#~ Re-write urls for PHP documents.
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

#~ redirect site/subfolder to site/subfolder.php
RewriteCond %{REQUESTFILENAME} !-f
RewriteRule ^(.*)/$ $1.php

这会将 URL 从 site.com/something.php 更改为 site.com/something 但最后一点没有按预期工作,我有一个文件夹 site.com/myfolder/,当用户转到“site.com/myfolder”时,我希望显示 site.com/myfolder.php 而不是实际文件夹。这实际上现在发生了,但是它像在子文件夹中而不是在根目录中一样踩踏页面,因此所有相关 url 都被破坏了,任何人都可以想到解决方案吗?

我的最终解决方案: [编辑] 在下面发布了完整的脚本。

【问题讨论】:

    标签: .htaccess web


    【解决方案1】:

    是否要将/myfolder 而不是/myfolder/ 重写为myfolder.php?尝试在您的 .htaccess 隐藏文件中使用此代码:

    Options +FollowSymlinks
    RewriteEngine on
    
    RewriteCond %{REQUEST_URI} ^/([a-z0-9-_]+)$
    RewriteRule ^(.*) /%1.php
    

    但是如果你想重定向它而不是被重写,那么只需在代码上的.php之后添加(一个空格和一个)[R]标志。不然呢?

    【讨论】:

    • 不,我只是想重写所有 php url,这对于与文件夹具有相同名称的 php 文件来说是不可能的,因为服务器会优先处理文件夹并忽略文件,因此它会添加一个尾部斜杠。因此,唯一的解决方案是使用“DirectorySlash Off”,我现在注意到我忘记将该行添加到我的解决方案中,我现在将对其进行编辑以供将来参考。
    【解决方案2】:

    使用 DirectorySlash Off 后出现的最后一个问题是该网站只能通过http://mysite.com/ 而不是http://mysite.com 访问

    所以你需要通过一个简单的错误重定向来解决这个问题

    所以完整的解决方案是这样的:

    #~ Turn off displaying index for folders and give a error 403 instead.
    Options -Indexes
    
    #~ Set the error page to the top folder of your website ending with a slash, use a http adres to make it act like a re-direct.
    ErrorDocument 403 http://mysite.com/
    
    #~ Set default page for folders.
    DirectoryIndex index.php
    
    #~ Turn off directory slashes.
    DirectorySlash Off
    
    #~ Turn on rewrite engine
    RewriteEngine on
    
    #~ Re-write urls for PHP documents.
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^(.*)$ $1.php
    

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2017-12-05
      • 2012-10-15
      • 2012-11-23
      • 2011-06-13
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      相关资源
      最近更新 更多