How to rewrite URLs with .htaccess (removing id?=1)

Tags: , , ,

I’ve looked all over and have yet to figure out how to make this work, I’m sure it’s very simple for someone who knows what they’re doing. For starters, I have made sure that mod_rewrite is enabled and removing .php extensions is working so I know that isn’t the issue.

Currently I’m working on a forum, and what I’m trying to do is simply remove the ?id=1 aspect of the URL, so basically making the URL look like such:

Instead of

/Forum is a directory with a document named Topic.php

My current .htaccess looks like this:

Options -MultiViews
RewriteEngine on

RewriteRule ^(.+).php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

Any help would be appreciated.


Assuming you’ve changed the URLs in your application to use then try the following:

# Remove .php file extension on requests
RewriteRule ^(.+).php$ /$1 [R,L]

# Specific rewrite for /Forum/Topic/N
RewriteRule ^(Forum/Topic)/(d+)$ $1.php?id=$2 [END]

# Append .php extension for other requests
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ /$1.php [END]

Your original condition that checked %{REQUEST_FILENAME}.php isn’t necessarily checking the same “URL” that you are rewriting to – depending on the requested URL.

UPDATE: however how would I go about adding another ID variable, as in making look like

So, in other words /Forum/Topic/1/2 goes to /Forum/Topic.php?id=1&page=2. You could just add another rule. For example:

# Specific rewrite for /Forum/Topic/N
RewriteRule ^(Forum/Topic)/(d+)$ $1.php?id=$2 [END]

# Specific rewrite for /Forum/Topic/N/N
RewriteRule ^(Forum/Topic)/(d+)/(d+)$ $1.php?id=$2&page=$3 [END]

Alternatively, you can combine them into one rule. However, this will mean you’ll get an empty page= URL parameter when the 2nd paramter is omitted (although that shouldn’t be a problem).

# Specific rewrite for both "/Forum/Topic/N" and "/Forum/Topic/N"
RewriteRule ^(Forum/Topic)/(d+)(?:/(d+))?$ $1.php?id=$2&page=$3 [END]

The (?:/(d+))? part matches the optional 2nd parameter. The ?: inside the parenthesis makes it a non-capturing group (otherwise we end up with an additional capturing subpattern that matches /2) and the trailing ? makes the whole group optional.

Source: stackoverflow