Nidhi
Nidhi

Reputation: 95

SEO Friendly URI using HTACCESS

I am new in PHP. I have my URL like below

http://localhost/index.php?page=20
http://localhost/user.php?id=15&localtion=delhi
http://localhost/folder/profile.php?id=15&active=today

What I am looking for convert my URL like below

http://localhost/page/20
http://localhost/user/id/15/localtion/delhi
http://localhost/folder/profile/id/15/active/today

I am trying from many hours to make it working with .htaccess file but no luck yet

one of little working code is like below

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

its removing .php from URL like below

http://localhost/index?page=15

I have checked many questions and answer in stackoverflow like below

https://stackoverflow.com/questions/41390397/htaccess-seo-friendly-url
https://stackoverflow.com/questions/41439512/php-url-replace-question-mark-and-parameter-with-slash
https://stackoverflow.com/questions/12451886/htaccess-for-friendly-url-with-multiple-variables

but not able to achieve my goal. Let me know if anyone expert here can help me for doing same and still my php code work fine without any issue.

Thanks a lot!

Upvotes: 3

Views: 260

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133770

With your shown samples, please try following htaccess rules. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
##Rule for external rewrite.
##Rule to handle from http://localhost/index.php?page=20 to http://localhost/page/20
RewriteCond %{THE_REQUEST} \s/index\.php\?([\w-]+)=(\d+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

##Rule for external rewrite.
##Rule to handle from http://localhost/user.php?id=15&localtion=delhi TO http://localhost/user/id/15/localtion/delhi
RewriteCond %{THE_REQUEST} \s/(user)\.php\?([\w-]+)=(\d+)&([\w-]+)=([\w-]+)\s [NC]
RewriteRule ^ /%1/%2/%3/%4/%5? [R=301,L]

##Rule for external rewrite.    
##Rule to handle from http://localhost/folder/profile.php?id=15&active=today To http://localhost/folder/profile/id/15/active/today
RewriteCond %{THE_REQUEST} \s/(folder)/(profile)\.php\?([\w-]+)=(\d+)&([\w-]+)=([\w-]+)\s [NC]
RewriteRule ^ /%1/%2/%3/%4/%5/%6? [R=301,L]

##internal rewrite rule to handle files internally.    
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?$ $1/$2.php?$3=$4&$6=$6 [QSA,L]

##internal rewrite rule to handle files internally.    
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?$ $1.php?$2=$3&$4=$5 [QSA,L]

##internal rewrite rule to handle files internally.    
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/?$ index.php?$1=$2 [QSA,L]

Upvotes: 3

Related Questions