【问题标题】:.htaccess resolve relative path issue.htaccess 解决相对路径问题
【发布时间】:2018-12-09 08:14:54
【问题描述】:

我是 .htaccess 文件的新手。在我的网站上,我有页面供用户按类别搜索书籍并按一些参数排序。真正的页面网址是这样的。我使用了一些具有相对路径的 css 和 js 文件。例如:<link href="../css/mystyle.css" rel="stylesheet">

www.example.com/post/index.php?cat=science-fiction&sort=date

我已经使用 .htaccess 文件修改了这个 url。获得更有意义的 url 体验。

#Turn Rewrite Engine On
RewriteEngine on

#Rewrite for ads.php
RewriteRule ^([0-9a-zA-Z_-]+) index.php?cat=$1 [NC,L]

我想要这样的网址。及其工作。

www.example.com/post/science-fiction

www.example.com/post/science-fiction?sort=date

但我的问题是,当用户输入网址末尾的"/" 时。页面无法加载 css 或 js 文件。我想重定向或忽略 URL 末尾的 "/"

这个网址有问题

www.example.com/post/science-fiction/

www.example.com/post/science-fiction/?sort=date

如何解决这个不断变化的 .htaccess 文件

【问题讨论】:

    标签: php .htaccess url redirect url-rewriting


    【解决方案1】:

    您可以在站点根目录 .htaccess 中使用这些规则:

    RewriteEngine on
    
    ## Unless directory, remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)/$ /$1 [NE,R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\w-]+)$ index.php?cat=$1 [QSA,L]
    

    对于长期方法,请考虑在 css 中使用绝对路径,如下所示:

    <link href="/css/mystyle.css" rel="stylesheet">
    

    【讨论】:

    • 目前我正在 localhost 中测试这个。此代码重定向到http://localhost/science-fictionhttp://localhost/science-fiction 如何重定向到http://localhost/Project/post/science-fictionhttp://localhost/Project/post/science-fiction?sort=date
    • 它的工作。我将其更改为 R=404。现在它重定向到 404。
    猜你喜欢
    • 2019-08-01
    • 2014-09-15
    • 2019-10-24
    • 1970-01-01
    • 2014-05-09
    • 2016-01-08
    • 2011-04-29
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多