smarvel
smarvel

Reputation: 40

.htaccess - clean urls with different parameters

Is there a way to get this to work?

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

The urls should look like this:

http://test.com/a/b
or
http://test.com/a/c

It only works with the first rule.

In my case I'm trying to create a profile page and get the ID either of the session ID or via $_GET['id'].

So if I visit a profile of someone else the url is

index.php?page=profile&id=25
/profile/25

And if I'm visiting my own profile it is

index.php?page=profile
/profile

And for example I want to edit my profile it is

index.php?page=profile&action=edit
/profile/edit

I hope you understand what I mean and can help me.

Upvotes: 0

Views: 1117

Answers (1)

Gerrit0
Gerrit0

Reputation: 9182

The key to solving this is noticing the differences between each parameter you want to pass.

  • If the visitor is looking at someone else's profile, an id (numeric) is passed.
  • If the visitor is editing their profile, a parameter string (alphanumeric) is passed
  • If the visitor is looking at their own profile, or another generic page, no extra parameters are passed

.htaccess rules can be most easily written from the most specific to the most general, so translating this, the rules become

RewriteRule ^([^/]+)/([0-9]+)$ index.php?page=$1&id=$2 [L]
RewriteRule ^([^/]+)/([a-z0-9]+)$ index.php?page=$1&action=$2 [NC,L]
RewriteRule ^([^/]+)$ index.php?page=$1 [L]

It is also important to skip existing files & directories, however because RewriteCond statements only match the next RewriteRule, it is easiest to do this in a slightly different way than you are doing it.

RewriteEngine On

# If the file or directory exists, exit
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .? - [END]

RewriteRule ^([^/]+)/([0-9]+)$ index.php?page=$1&id=$2 [L]
RewriteRule ^([^/]+)/([a-z0-9]+)$ index.php?page=$1&action=$2 [NC,L]
RewriteRule ^([^/]+)$ index.php?page=$1 [L]

Upvotes: 1

Related Questions