-1

我希望地址栏显示的内容:

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="...">强制路径页面正确显示。但我想在没有它的情况下解决我的问题。

如何删除地址栏中的尾部斜杠?重写似乎按预期工作。

4

2 回答 2

1

Your issue is that when you someone access http://domain.com/user/photos for example, the css, js and other relative links in the page resolves to http://domain.com/user/css/main.css (for example).

You have two solutions for this :

  • Add base tag in head section of the page (wich you tried already)
  • Change all relative links in your page absolute links (wich I don't recommand you)

So the easier solution is to use the base tag.

Note: Even if you remove the slash in the end, it may work for http://domain.com/user/ but will definitly not work for http://domain.com/user/photos

于 2012-09-14T10:07:06.923 回答
1

When you are going to use Friendly URLs, you must use absolute paths for your resources.

Initial Declaration

You might have declared index.php with this way:

<link rel="stylesheet" href="stylesheets/styles.css" />
<img src="assets/user.png" />
<script type="text/javascript" src="scripts/home.js"></script>

Proposed Way using / for Absolute Paths

But it has to be translated this way:

<link rel="stylesheet" href="/stylesheets/styles.css" />
<img src="/assets/user.png" />
<script type="text/javascript" src="/scripts/home.js"></script>

Notice the / in the front to make them as Absolute URLs.

Using <base href="/" />

If this is going to be a tedious task for you, you can use this tag:

<base href="/" />

This will make your Relative URLs to relate with the Root.

Using a $baseurl variable

Another better way is to prepend with a $baseurl variable.

<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>

This way, you can even change the $baseurl value if you are hosting in a folder and not in the root!

于 2012-09-14T10:07:53.287 回答