php – friendly URL does not retrieve variable

Question:

I'm trying to make my site's URLs user-friendly.

friendly URL

 http://localhost/mg/artista/10 

.htaccess

<IfModule mod_rewrite.c>
  RewriteEngine On

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

  RewriteRule ^/artista/([0-9]+)$ /artista.php?artista=$1
</IfModule>

PHP to retrieve the variable

$artista = $_GET['artista']; 

It's giving the following error: Notice: Undefined index: artist

I saw in some places people retrieving the variable using $_SERVER['REQUEST_URI']. If I use this, it returns: /mg/artista/10. Exploding would get the variable, but I don't know if that's the correct way.

Answer:

The problem with your .htaccess is that in the rule

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

the ^/ at the beginning indicates that the path must start with /artista . As in your case the path starts with mg/ , the rule is skipped.

For it to work you just need to remove the ^/ from the beginning of the rule.

Ex.:

<IfModule mod_rewrite.c>
  RewriteEngine On

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

  RewriteRule /artista/([0-9]+)$ /artista.php?artista=$1
</IfModule>

Note: In case you don't know, here you can find a very good tool to test htaccess.

Scroll to Top