Cameron Mark Lewis Cameron Mark Lewis - 7 months ago 51
PHP Question

URL Rewrite Optional Parameter

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

properties.php?bed=1&page=1&perpage=12&area=testarea
to
/search/1/1/12/testarea
. 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} ^www.studentlettingsagency.co.uk$ [OR]
RewriteCond %{HTTP_HOST} ^studentlettingsagency.co.uk$
RewriteRule ^(.*) http://www.stla.co.uk/$1 [QSA,L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
</IfModule>


Any help would be great!

Answer

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