.htaccess question - URL-rewriting

2019-09-07 12:52发布

I have an issue with URL-rewriting in .htaccess. Here is .htaccess file:

RewriteEngine On
RewriteBase /community/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^view-all-results$ forums/index.php?view=view-all-results [R=302]
RewriteRule ^view-all-results/$ forums/index.php?view=view-all-results [R=302]

I need to rewrite url like "/community/view-all-results?u=2" to "community/forums/index.php?view=view-all-results&u=2". But according to the above rule I'll get "community/forums/index.php?view=view-all-results".

I tried to change RewriteRule to

RewriteRule ^view-all-results?(.*)$ forums/index.php?view=view-all-results&$1 [R=302]

But it doesn't work properly. It still rewrites URL to "community/forums/index.php?view=view-all-results".

When I changed rule(put + instead of *):

RewriteRule ^view-all-results?(.+)$ forums/index.php?view=view-all-results&$1 [R=302]

I've got URL like "community/forums/index.php?view=view-all-results&s". So I don't understand this behavior.((

I will be very appreciated for any suggestions.

2条回答
虎瘦雄心在
2楼-- · 2019-09-07 13:34

The magic flag is in the docs: [QSA], which will add the original querystring to your url.

Normal matching is only done against the path, not agains the querysting, which you would find in the magic variable %{QUERY_STRING}). Matching this variable can be done in a RewriteCond condition. You could also append this variable to the resulting url, but QSA is infinitely more userfriendely here.

查看更多
一纸荒年 Trace。
3楼-- · 2019-09-07 13:47

Give this a try...

RewriteEngine On
RewriteBase /community/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^view-all-results/?$ forums/index.php?view=view-all-results [QSA]

Basically the first half of a RewriteRule doesn't match against the QUERY_STRING, so you second to example will never match against it. The main thing your first code was missing was the QSA flag, which tells it to pass the QUERY_STRING it receives along with the newly created QUERY_STRING. I also removed the R=302, as I assume you don't want the URL to change.

Edit: Oh, I also combined the rules by making the trailing slash optional.

查看更多
登录 后发表回答