.htaccess 解决相对路径问题 [英] .htaccess resolve relative path issue
问题描述
我是 .htaccess 文件的新手.在我的网站上,我有页面供用户按类别搜索书籍并按某些参数排序.真正的页面网址是这样的.我使用了几个带有相对路径的 css 和 js 文件.例如:
I'm new to .htaccess files. In my website i have page for users to search books by its category and sort by some parameters. real page url is like this. I have used few css and js files with relative paths. Ex: <link href="../css/mystyle.css" rel="stylesheet">
www.example.com/post/index.php?cat=science-fiction&sort=date
www.example.com/post/index.php?cat=science-fiction&sort=date
我使用 .htaccess 文件修改了这个 url.获得更有意义的网址体验.
I have modified this url by using .htaccess file. for more meaningful url experience.
#Turn Rewrite Engine On
RewriteEngine on
#Rewrite for ads.php
RewriteRule ^([0-9a-zA-Z_-]+) index.php?cat=$1 [NC,L]
我想要这样的网址.及其工作.
I wanted to have my urls like this. and Its working.
www.example.com/post/science-fiction
www.example.com/post/science-fiction
www.example.com/post/science-fiction?sort=date
www.example.com/post/science-fiction?sort=date
但我的问题是,当用户输入 url 的 "/"
结尾时.页面无法加载 css 或 js 文件.我想重定向或忽略 URL 的 "/"
结尾.
But my problem is, when user enters "/"
end of the url. Page cant load css or js files. I want to Redirect or Ignore "/"
end of the Url.
这个网址有问题
www.example.com/post/science-fiction/
www.example.com/post/science-fiction/
www.example.com/post/science-fiction/?sort=date
www.example.com/post/science-fiction/?sort=date
如何解决这个不断变化的 .htaccess 文件
How to resolve this changing .htaccess file
推荐答案
您可以在站点根目录 .htaccess 中使用这些规则:
You can use these rules in your site root .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 中使用绝对路径,如下所示:
For long term approach consider using absolute path in css like this:
<link href="/css/mystyle.css" rel="stylesheet">
这篇关于.htaccess 解决相对路径问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!