Gungor Budak
Gungor Budak

Reputation: 150

Handling Two Query Strings with .htaccess

I'm trying to rewrite urls for a page that has two query strings parameter. And according to these parameters value (set or not), I show different contents on the page.

example.com/fotograf.php?aid=10
example.com/fotograf.php?aid=10&fid=5

The URLs above are the examples to not rewrited ones. I just want to make them such that

example.com/fotograf/10/
example.com/fotograf/10/5/

The first URL links to the album with photos, and the second one links to a photo in that album.

In .htaccess, I just want to be able to reach them with the clean URLs above. After that, I will check the URL at the top of the script and if it's not clean then with a function I wrote I will redirect it to clean one (by getting values with preg_match and preg_split and redirecting with header function).

So far, I have tried this rule (which did not work to view album):

RewriteRule ^fotograf/([0-9-/]+)/([0-9]+)/?$ fotograf.php?aid=$1&fid=$2 [L]

Then, this (which redirects to album always):

RewriteRule ^fotograf/([0-9-/]+)/?$ fotograf.php?aid=$1 [L]

Finally, this (helped me to view the photo by a URL like example.com/fotograf/10/?fid=5):

RewriteCond %{QUERY_STRING} ^fid=(.*)$
RewriteRule ^fotograf/(.*)/$ fotograf.php?aid=$1&fid=%1

But I don't want to see any question marks or ampersands in the URL.

Somehow, I need to check which one(s) is(are) set and redirect accordingly but I just don't know how to achieve this.

How can I do this?

Thanks in advance.

Upvotes: 3

Views: 4347

Answers (2)

taggart
taggart

Reputation: 11

# this works 
  RewriteEngine On
  RewriteBase /yourdir/yourfolder/

# only 1 in root 
# RewriteRule ^([a-zA-Z0-9-]+)$ index.php?act=$1[L,QSA]

  RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/?$ members.php?act=$1&opts=$2

  RewriteRule ^([a-zA-Z0-9-]+)/?$ members.php?act=$1

 #   Your url would be:
 #   example of http://localhost/yourdir/yourfolder/members.php?act=beer
 #   http://localhost/yourdir/yourfolder/beer
 # or 
 # http://localhost/yourdir/yourfolder/members.php?act=beer&ops=morebeer
 # http://localhost/yourdir/yourfolder/beer/morebeer

Upvotes: 1

Kamil Šrot
Kamil Šrot

Reputation: 2221

You need to make your application to generate the URLs like you want them, so in the form:

example.com/fotograf/10/
example.com/fotograf/10/5/

and following rewrite rule will make sure, it'll reach your php:

RewriteEngine On

RewriteRule ^fotograf/([0-9]+)/([0-9]+)/?$ fotograf.php?aid=$1&fid=$2

RewriteRule ^fotograf/([0-9]+)/?$ fotograf.php?aid=$1

mod_rewrite can't rewrite URLs in your HTML pages...

Upvotes: 3

Related Questions