开发者

How to setup optional parameters in mod_rewrite

I am in a new project and I'm designing the URL structure, the thing is I want URLs look like this: /category-23/keyword/5/ Where the normal page is: /search.php?q=keyword&cat=23&a开发者_运维知识库mp;page=5 So my question is, cat and page fields, must be optional, I mean if I go to /keyword it should be /search.php?q=keyword (page 1) and if I go to /category/keyword should be: /search.php?q=keyword&cat=category&p=1 and also if I go to /keyword/5/ it must be: /search.php?q=keyword&p=5

Now I have my .htaccess like this:

RewriteEngine On
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*)$ search.php?q=$2&cat=$1&page=$3 [L]

I cannot make it working and the CSS / image files don't load. I'd thank a lot who could give me a solution.


You can do this with four rules, one for each case:

RewriteRule ^([^/]+)$ search.php?q=$1
RewriteRule ^([^/]+)/([0-9]+)$ search.php?q=$2&p=$1
RewriteRule ^([^/]+)/([^/]+)$ search.php?q=$2&cat=$1&p=1
RewriteRule ^([^/]+)/([^/]+)/([0-9]+)$ search.php?q=$2&cat=$1&p=$3

And with this rule in front of the other rules, any request that can be mapped onto existing files will be passed through:

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^ - [L]

Now your last issue, that externally linked resources cannot be found, is due to that you’re probably using relative URL paths like css/style.css or ./css/style.css. These relative references are resolved from the base URL path that is the URL path of the URL of the document the references are used in. So in case /category/keyword is requested, a relative reference like css/style.css is resolved to /category/keyword/css/style.css and not /css/style.css. Using the absolute URL path /css/style.css makes it independent from the actual base URL path


While i know this was answered succinctly by @Gumbo a few months back, I ran into a similar issue recently... and didn't want to include full/absolute paths in my app, to keep it dynamic and not having a bunch APP_PATH (php) vars all over the place... so I just added a base[href] html tag with the

like so...

<base href="http://<?php echo $_SERVER[HTTP_HOST];?><?php echo APP_PATH;?>"/>

Hoping that helps others... and this is not trying to discount @Gumbo's reply in the least... they're right-e-o on :).


Shouldn't it be

RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule ^ - [L]

in @Gumbo's answer above? Works with me like that. If it is a file (like CSS), let it pass through.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜