【问题标题】:.htaccess Remove URL Extension, Add Trailing Slash.htaccess 删除 URL 扩展名,添加尾部斜杠
【发布时间】:2012-04-15 08:36:02
【问题描述】:

我一直试图让它在我正在开发的网站的客户服务器上工作,但我根本无法让它工作。基本上我正在尝试删除 .html 扩展名,并添加一个斜杠(在 URL 栏中)。

所以如果有人进入:

-example.com/home/ ----------- 转到 ----- example.com/home/

-example.com/home ------------ 转到 ----- example.com/home/

-example.com/home.html ------ 转到 ----- example.com/home/

-example.com/home.html/ ----- 转到 ----- example.com/home/

-example.com/home/.html ----- 转到 ----- example.com/home/

-example.com/home/.html/ ---- 转到 ----- example.com/home/

到目前为止,这是我的 .htaccess,它可以完美运行,并且可以完成我想做的所有事情,除了在末尾添加斜杠。

代码如下:

#force www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*) http://www.%{HTTP_HOST}/1 [R=301,L]

# remove .html ONLY if requested directly
RewriteCond %{THE_REQUEST} (\.html\sHTTP/1)
RewriteRule ^(.+)\.html /1 [R=301,L,QSA]

# remove trailing slash ONLY if it is not an existing folder
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/ /1 [L,R=301]

# rewrite to FILENAME.html if such file does exist and is not a folder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*) /1.html [L,QSA]

我在服务器上托管的所有文件都是 FILENAME.html 的形式,并且位于根目录中。

所以,如果有人能帮助我,我将不胜感激。

【问题讨论】:

    标签: apache .htaccess web


    【解决方案1】:

    修改.htaccess文件,插入以下内容

    说明: http://eisabainyo.net/weblog/2007/08/19/removing-file-extension-via-htaccess/

    例子:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.html -f
    RewriteRule ^([^/]+)/$ $1.html 
    
    # Forces a trailing slash to be added
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
    RewriteRule (.*)$ /$1/ [R=301,L]
    

    更新页面上的链接

    然后,所有超链接、css 链接、图像等都需要更新为具有绝对 URL (http://www.site.com/style.css) 或相对 URL,并以 ../ 开头。否则会遇到 CSS 无法加载、链接失效等问题。

    【讨论】:

    • 不幸的是,我已经尝试过该解决方案,但它根本不适合我。我只是收到一个错误 404 not found 页面。我在 OP 中发布的 .htaccess 效果很好,只是没有在 URL 的末尾添加斜杠。
    • 我已经更新了答案。试试这个,清晰一点。
    • 这对我也不起作用。它添加了斜线,但不加载任何 CSS 或图像。最重要的是,当我点击我网站上的任何链接时,它只会将它们添加到 URL 栏中的任何内容中。假设我在 example.com/home/,然后我点击 test,然后不是去 example.com/test/,而是去 example.com/home/test。
    • 您的链接、CSS、图像等都需要是绝对的或相对的,但以“../”开头
    • 好的,我将 .htaccess 更改为您发布的代码,如果我输入没有 .html 扩展名的 URL,它会添加一个斜杠,但如果我用 .html 扩展名输入它仍然显示它。我希望 .html 扩展名自动消失,然后添加一个斜杠。
    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多