skip to Main Content

I’ve just started to use .htaccess and i’m having an issue here.

Inside my public_html folder i have these files.

  • index.php
  • profile.php
  • test.php
  • .htaccess

And when i go to profile.php file i have some parameters.

http://website.com/profile.php?id=1&name=Doe

For showing better SEO links i’m trying to make it appear like this

http://website.com/1/Doe

with this rewrite condition

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ profile.php?url=$1 [QSA,L]
</IfModule>

depended on this answer (click here)

and then in my php file i get the id of the user so i can make the queries etc with this code

$path_components = explode('/', $_GET['url']);
$ctrl=$path_components[0];

But the thing is that if i do so every file in my folder is trying to make the Rewrite Rule but i want a specific file… the profile.php one.

EDiT 1:

So from the comment below i made this htaccess file, and regardless the mod_rewrite is enabled on my server, the link is not changing at all.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/profile.php$ [NC]
    RewriteRule ^([^/.]+)/([^/.]+)(?:/)?$ /profile.php?id=$1&name=$2 [L]
</IfModule>

And my php file now..

$path_components = explode('/', $_GET['id']);
$ctrl=$path_components[0];

But the link

http://website.com/profile.php?id=1&name=Doe

is not changing at all.

2

Answers


  1. You need to redirect your old url to the new one, put this above your existing rule

    RewriteEngine on
    RewriteCond %{THE_REQUEST} /profile.php?id=([0-9]+)&name=(.+)sHTTP [NC]
    RewriteRule ^ /%1/%2? [L,R]
    RewriteRule ^([^/]+)/([^/]+)/?$ /profile.php?id=$1&name=$2 [L]
    
    Login or Signup to reply.
  2. Hello the issue is simple: you should exclude existing files/folders from rewriting process.
    I would recommend to have only one index.php page where you get all the request and process in one place. Anyway your working htaccess file should look like this:

    <IfModule mod_rewrite.c>
    
        RewriteEngine On
    
        # exclude real folders/files
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        #RewriteRule ^ index.php [L] - # redirect anything to index
        # for your version
        RewriteRule ^(.*)$ profile.php?url=$1 [QSA,L] 
    </IfModule>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search