【问题标题】:Hide .html and manage 404隐藏.html并管理404
【发布时间】:2021-04-02 22:31:56
【问题描述】:

我想在我的网站上做这个映射

xyz.html -> on /xyz
abc.html -> on /abc
index.html -> on /

我在我的 .htaccess 文件中写了这些规则

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !^$ !.*\.html$ %{REQUEST_FILENAME}.html [L]

但我有一些问题。

  • 404 错误不再起作用。如果我浏览 /hello 它给了我内部服务器错误
  • 如果我浏览到 /xyz.html -> /xyz(SEO 友好),我想要重定向

想要的行动:

/ -> serve index.html        
/abc -> serve abc.html       
/abc.html -> redirect to /abc      
/123.html -> throws 404      
/123/ -> throws 404 (now throws 500)

我该怎么做?提前谢谢你

【问题讨论】:

    标签: apache redirect mod-rewrite url-rewriting friendly-url


    【解决方案1】:

    您可以使用以下内容:

    RewriteEngine on
    
    #Remove .html extension
    #1)redirect "/file.html" to "/file"
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^([^.]+)\.html$ /$1 [L,R=301]
    #2) internally map /file to /file.html
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^([^/]+)/?$ /$1.html [L]
    #3) Redirect "index.html to "/"
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.html$ / [L,R=301]
    #Internally map homepage "/" to "index.html"
    RewriteRule ^$ /index.html [L]
    

    【讨论】:

    • 它创造了一种奇怪的行为。如果我包含例如 ../../file.js 它会变成 404,就像我只包含“file.js”
    • @FrancescoFattori 您需要使用 base 标签来修复您的 js 和其他相关资源。如果您使用相对路径链接 js 文件,那么该文件显然会得到 404,因为它正在寻找 URL 路径。例如,如果 URL 路径是 /file/ 而不是 file.html,那么您的相关资源将从 /file/ 加载,这不是目录而是重写的 html 文件。要解决此问题,请使您的链接成为绝对链接或使用基本标记。在您的网页标题中添加此<base href="/">,以便您的相关链接可以从正确的位置加载。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2012-03-02
    • 2011-01-26
    • 2011-04-21
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    相关资源
    最近更新 更多