Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite URL with .htaccess for multiple parameters

Tags:

.htaccess

This question might be a duplicate. But I did not find any solution worked for me. I want to rewrite URL, where I have one and two level parameters. first parameter is p and second is sp

www.domain.com/home should point to www.domain.com/index.php?p=home and www.domain.com/projects/99 should point to www.domain.com/index.php?p=projects&sp=99

How do I do in .htaccess?

Currently My htaccess is as followes,

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?p=$1
RewriteRule ^([^/]*)/([^/]*)\$ index.php?p=$1&sp=$2 [L]

The problem with this htaccess is that it correctly points one level url. ie., www.domain.com/home. But not the two level url. ie. www.domain.com/projects/99

like image 768
Firnas Avatar asked Feb 09 '13 08:02

Firnas


People also ask

How can I redirect and rewrite my urls with an .htaccess file?

Use a 301 redirect . htaccess to point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "example.com" domain.

What is $1 in Apache rewrite rule?

In your rewrite, the ^ signifies the start of the string, the (. *) says to match anything, and the $ signifies the end of the string. So, basically, it's saying grab everything from the start to the end of the string and assign that value to $1.

What is Apache rewrite rule?

A rewrite rule can be invoked in httpd. conf or in . htaccess . The path generated by a rewrite rule can include a query string, or can lead to internal sub-processing, external request redirection, or internal proxy throughput.


1 Answers

You have to treat the rules separately. All Conditions preceding rules only apply to a single rule. Following rules are not touched by peceding rule and their conditions. You tried to 'chain' two rules. The second rule never could have matched, since the first one was a catch-all that changed the syntax. Apart from that you have to make sure that the first rule does not catch unwanted requests. Also think about whether you want to use the * or the + operator in the patterns. I suggest you use the + operator, so that you have a clear error message when empty values are requested for a 'page' or a 'subpage'.

So this might come closer to what you are looking for:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?p=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ index.php?p=$1&sp=$2 [L]
like image 194
arkascha Avatar answered Sep 21 '22 08:09

arkascha