首页 > 解决方案 > 从 URL 中隐藏父目录,或允许链接不需要该父目录

问题描述

我有一个基于 PHP 的网站,我想让它更安全一点,对 SEO 更友好。我的网站有两个文件夹privatesite. 所有面向公众的页面、css、脚本、图像都在该site文件夹中。我所有的后端 PHP 代码都在该private文件夹中。目前,我正在通过使用Deny from all位于.htaccess文件夹中的文件来保护对私有文件夹的任何访问private。在我的本地服务器(当前使用 XAMPP)上,该项目位于我的htdocs文件夹中,并且有一个项目名称,我们会说是example_project. 在该site文件夹下,我还有一些其他子目录,用于整理我网站中页面的 CSS、JS、图像和一些主要子类别。我正在努力弄清楚如何制作它,以便(A)URL 不需要包含site在 URL 中以访问位于其下的任何内容,并且(B)它会更改包含在 URL 中的任何请求site以将其从路径中排除。

(A) 示例 example_project/subfolder/index.php访问example_project/site/subfolder/

(B) 示例 example_project/site/subfolder/index.php重定向到example_project/subfolder/

.htaccess几乎在每个目录中都有一个文件。在我的项目的顶层(请注意,这不是服务器 Web 根目录)我有以下.htaccess文件

<FilesMatch "\.(css|flv|gif|htm|html|ico|jpe|jpeg|jpg|js|png|pdf|swf|txt|php)$">
    #Used to allow for content expiration
    <IfModule mod_expires.c>
        ExpiresActive Off
    </IfModule>
    <IfModule mod_headers.c>
        FileETag None
        Header unset ETag
        Header unset Pragma
        Header unset Cache-Control
        Header unset Last-Modified
        Header set Pragma "no-cache"
        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
        Header set Expires "Mon, 10 Apr 1972 00:00:00 GMT"
    </IfModule>
</FilesMatch>

RewriteEngine On

#Force site to require https
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#Allow links not to have the .php file extension
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#THIS IS WHAT I AM HAVING TROUBLE WITH
RewriteRule ^$ site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^site /example_project/site/$1 [NC,L]

编辑 请注意,我还记得添加一个捕获组,所以最后一行现在读作RewriteRule !^site/([-/\w]+) /hb1/site/$1 [NC,L]

标签: phpapache.htaccessmod-rewrite

解决方案


注释掉前 2 个http->https.php规则并使用这些规则进行测试

RewriteEngine On

RewriteRule ^$ site/ [L]

RewriteRule ^(?!site/).* site/$0 [NC,L]

推荐阅读