我希望地址栏显示的内容:
http://facebook.com/user
http://facebook.com/user/ -> http://facebook.com/user
http://facebook.com/user/photos -> http://facebook.com/user/photos
我的重写规则:
RewriteEngine On
RewriteRule ^(.+)/$ $1 [NC]
RewriteRule ^([A-Za-z0-9_-]+)/?([A-Za-z0-9_-]*)$ user.php?id=$1&second=$2 [NC,L]
发生了什么:
1). http://domain.com/user (working well)
2). http://domain.com/user/ (keeps the / in the address bar and destroys css/js/img paths)
3). http://domain.com/user/photos (same result as 2, correct except the paths)
如果使用<base href="...">
强制路径,则页面将正确显示。但我想在没有它的情况下解决我的问题。
如何删除地址栏中的尾部斜线?重写工作似乎按预期进行。
当您要使用友好URL时,您必须使用资源的绝对路径。
初始声明
您可能已经用这种方式声明了index.php
:
<link rel="stylesheet" href="stylesheets/styles.css" />
<img src="assets/user.png" />
<script type="text/javascript" src="scripts/home.js"></script>
用/
求绝对路径的方法
但它必须这样翻译:
<link rel="stylesheet" href="/stylesheets/styles.css" />
<img src="/assets/user.png" />
<script type="text/javascript" src="/scripts/home.js"></script>
注意前面的/
使它们成为绝对URL。
使用<base href="/" />
如果这对你来说是一项乏味的任务,你可以使用这个标签:
<base href="/" />
这将使您的相对URL与根相关。
使用$baseurl
变量
另一种更好的方法是使用$baseurl
变量进行预处理。
<link rel="stylesheet" href="<?php echo $baseurl; ?>/stylesheets/styles.css" />
<img src="<?php echo $baseurl; ?>/assets/user.png" />
<script type="text/javascript" src="<?php echo $baseurl; ?>/scripts/home.js"></script>
这样,如果托管在文件夹中而不是根目录中,您甚至可以更改$baseurl
值!
您的问题是,例如,当您有人访问http://domain.com/user/photos
时,页面中的css、js和其他相关链接会解析为http://domain.com/user/css/main.css
(例如)。
您有两种解决方案:
- 在页面的标题部分添加基标记(您已经尝试过了)
- 更改页面中的所有相对链接绝对链接(我不建议您这样做)
因此,更简单的解决方案是使用基本标记。
注意:即使最后删除斜杠,它也可能适用于http://domain.com/user/
,但绝对不适用于http://domain.com/user/photos