【问题标题】:Subfolder/Subdirectory and clean URL's子文件夹/子目录和干净的 URL
【发布时间】:2015-12-10 13:07:29
【问题描述】:

在进行大量测试并深入研究 stackoverflow 之后,我无法弄清楚如何实现这一点。

我在子文件夹 (www.domain.com/subfolder/) 中有一个网站。我的 .htaccess 位于该子文件夹 (www.domain.com/subfolder/.htaccess) 中,并且我有 3 个 html (index.html, example1.html, example2.html)

我希望当您访问 www.domain.com/subfolder/example2.html 时,它会打开 www.domain.com/subfolder/example2/ 并使用干净的 url 并且 css、js 和图像路径正常工作。

我不知道如何将此子文件夹设置为 root 并继续使用干净的 url。

这是我实际的 .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

我尝试了几件事,但似乎没有任何效果。

提前致谢。 迭戈

【问题讨论】:

    标签: .htaccess subdirectory clean-urls


    【解决方案1】:

    /subfolder/.htaccess试试这个:

    RewriteEngine On
    RewriteBase /subfolder/
    
    # To externally redirect /subfolder/file.html to /subfolder/file/
    RewriteCond %{THE_REQUEST} \s/+(.+?)\.html[\s?] [NC]
    RewriteRule ^ /%1/ [R=302,L]
    
    ## To internally redirect /subfolder/file/ to /subfolder/file.html
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.+?)/?$ $1.html [L]
    

    对于css,js,image 等,请确保在您的 HTML 中使用绝对路径,否则您可以将其添加到页面 HTML 的 <head> 部分下方:<base href="/" /> 以便每个 相对 URL 都是从该基本 URL 而非当前页面的 URL 解析。

    【讨论】:

    • Anubhawa,我很好奇,为什么我们需要在 THE_REQUEST 中匹配斜线/+ 1 次或多次?
    • 您好 Anubhava,已经尝试过了,但不起作用。当我访问www.domain.com/subfolder/时,它会在www.domain.com中查找css、图像和js,当我尝试访问www.domain.com/subfolder/example2.html时,它会转到www.domain.com/example2/而不是www.domain.com/subfolder/example2/
    • @Starkeen:理论上有人也可以输入http://domain.com////subfolder/file.html作为URL
    • @anubhava 你说得对。现在的问题是css、图像和js。如果我在localhost/subfolder/example2/ 上并单击指向“example1.html”的链接,它将转到localhost/subfolder/example2/example1/
    • 如果您可以访问 Apache 服务器,是的,那么您肯定可以
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2013-10-21
    • 2015-04-22
    • 2015-04-06
    • 2015-02-13
    • 2013-12-02
    相关资源
    最近更新 更多