mod_rewrite和尾部斜杠

I have

RewriteRule    ^([A-Za-z0-9-_≈]+)/?$    page.php?text=$1

to translate hits like domain.com/sample_text into page.php?text=sample_text

However, I want the following two conditions to also work (and give the same result).

1) If they go to domain.com/sample_text/ I want to keep the trailing slash in the adress bar and show page.php?text=sample_text (now it goes to the right page but the css and js-paths are messed up).

2) If they go to domain.com/sample_text/worthlessdata123 I want to strip everything after the /, keeping domain.com/sample_text/ in the adress bar and show page.php?text=sample_text.

I've struggled quite a bit, but I'm lousy at regex and my head isn't working properly.

The rules you have should suffice for the first condition. If someone goes to domain.com/sample_text/, the URI sample_text/ matches and should get served the content at /page.php?text=sample_text while the browser's URL address bar remains unchanged.

For the second condition, you need to add a rule to handle that:

RewriteRule ^([A-Za-z0-9-_≈]+)/.+$ /$1/ [L,R=301]

This will redirect: domain.com/sample_text/worthlessdata123 to domain.com/sample_text/, then the first rule should take things from there.


Misread what your first issue was. The relative/absolute paths you have in your page content is getting a different base because of the extra slash. When you have something like <img src="images/blah.gif">, the relative base is derived from the URL the browser sees (not what is internally re-written by the server). So if the browser sees: http://domain.com/sample_text, the URI base is /, but when the browser sees http://domain.com/sample_text/, the URI base becomes /sample_text/, which I'm guessing isn't where somethin glike images/blah.gif resides.

You can fix this by including the base in the header of your pages:

<base href="/">

The first problem you need to solve by using absolute paths for your assets (js, images, etc.)

For the second problem, you need @Jon Lin's solution.