ahmad ali
ahmad ali

Reputation: 1245

How to write htaccess rewrite rule for seo friendly url

I want:

demo.example.com/section.php?id=1 

Changed to:

demo.example.com/section/sample-section

i tried

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^section/(\d+)*$ ./section.php?id=$1

but no difference

Thanks.

I will appreciate your help.

Upvotes: 7

Views: 52091

Answers (2)

Axiom
Axiom

Reputation: 902

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

This will turn example.com/section.php?id=X to example.com/section/X

I suggest storing the URI in a database then using section.php?uri=

For example:

example.com/section.php?uri=super-awesome

would turn into:

example.com/section/super-awesome

Upvotes: 6

Justin Iurman
Justin Iurman

Reputation: 19016

First, make sure mod_rewrite is enabled and htaccess files allowed in your Apache configuration.

Then, put this code in your htaccess (which has to be in root folder)

Options -MultiViews
RewriteEngine On

# redirect "/section.php?id=xxx" to "/section/xxx"
RewriteCond %{THE_REQUEST} \s/section\.php\?id=([0-9]+)\s [NC]
RewriteRule ^ /section/%1? [R=301,L]

# internally rewrite "/section/xxx" to "/section.php?id=xxx"
RewriteRule ^section/([0-9]+)$ /section.php?id=$1 [L]

Upvotes: 12

Related Questions