views:

28

answers:

1

Hi all, 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&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.

A: 

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

Gumbo
sergip
And works perfectly!
sergip