Cameron Mark Lewis Cameron Mark Lewis - 2 years ago 161
PHP Question

URL Rewrite Optional Parameter

I'm trying to get a my original url which would have been

. But the last query string 'area' is optional and so could be blank.

I have this so far below, the problem is if I add an extra ([^/]+)/ such and

RewriteRule search/([^/]+)/([^/]+)/([^/]+)/([^/]+)/? pages/properties.php?bed=$1&page=$2&perpage=$3&area=$4

and then don't supply an area in the url, it fails to work correctly. Is there a correct way to do this where the query sting can be optional?

Also another problem I'm having is I would like this

RewriteRule search-rooms/([^/]+)/([^/]+)/([^/]+)/? pages/rooms.php?bed=$1&page=$2&perpage=$3&area=$4

to be /search/rooms/ not /search-rooms/ but if I put an extra / after search it again doesn't work correctly and the page reads the wrong data from the URL.

This is the full version

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule property/([^/]+)/? pages/show.php?id=$1 [NC,L]
RewriteRule search/([^/]+)/([^/]+)/([^/]+)/? pages/properties.php?bed=$1&page=$2&perpage=$3&area=$4 [L,QSA,NC]
RewriteRule search-rooms/([^/]+)/([^/]+)/([^/]+)/? pages/rooms.php?bed=$1&page=$2&perpage=$3&area=$4 [L,QSA,NC]
RewriteCond %{HTTP_HOST} ^$ [OR]
RewriteCond %{HTTP_HOST} ^$
RewriteRule ^(.*)$1 [QSA,L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

Any help would be great!

Answer Source

You can use the following rule :

RewriteCond %{REQUEST_URI} !^/search/rooms
RewriteRule search/([^/]+)/([^/]+)/([^/]+)/?([^/]*)?/?$ pages/properties.php?bed=$1&page=$2&perpage=$3&area=$4 [NC,L]
RewriteRule search/rooms/([^/]+)/([^/]+)/([^/]+)/?([^/]*)?/?$ pages/rooms.php?bed=$1&page=$2&perpage=$3&area=$4 [NC,L]

RewriteCond is important here ,as it tells the first rule not to match the uri /search/rooms

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download