Reputation: 673
I'm trying to hide part of url and show only the variables like directories.
For example: Change from https://somesite.com/users.php?user=Alex
to https://somesite.com/Alex/
or from https://somesite.com/users.php?user=Alex&tab=photos
to https://somesite.com/Alex/photos/
.
My .htaccess
:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# hide GET variables from url for messages page.
RewriteRule ^messages/(.*) messages.php?message=$1 [L,QSA]
# hide users.php and transforming variables in directories.
RewriteRule ^/%1 users.php?user=$1 [L,QSA]
</IfModule>
But, if I access https://somesite.com/users.php?user=Alex
nothing happens and if I access https://somesite.com/Alex/
error 404 is returned.
Upvotes: 2
Views: 70
Reputation: 4891
I don't see how could the last RewriteRule
do what you want.
You could use this instead:
RewriteRule ^([^/]+)/?$ users.php?user=$1 [L,QSA]
RewriteRule ^([^/]+)/([^/]+)/?$ users.php?user=$1&tab=$2 [L,QSA]
Edit: You can also use mod_rewrite to redirect those who use the old url to new url. This should work:
RewriteCond %{QUERY_STRING} ^user=([^&]+)$
RewriteRule ^/users.php$ /%1/ [L,R=301]
RewriteCond %{QUERY_STRING} ^user=([^&]+)&tab=([^&]+)$
RewriteRule ^/users.php$ /%1/%2/ [NC,L,R=301]
Alternative;y you can read REQUEST_URI
variable in php (it should contain the address before rewrite) and detect if it was the old one. If it was, then redirect to the new one.
Upvotes: 1
Reputation: 1312
It seems that the easiest solution is to send every query to index.php?q=$1 or another script.php to manage the path:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?q=$1 [QSA,L]
</IfModule>
index.php can check both cases:
<?php
$q = explode('/',$_GET['q']);
$query=$q[0];
if($query=='messages'){
$message = $q[1];
require "messages.php";
}else{
$user = $query;
require "users.php";
}
?>
Upvotes: 1
Reputation: 2772
Please write this code in your .htaccess file
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^([A-Za-z0-9-]+)/?$ users.php?user=$1 [NC,L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ users.php?user=$1&tab=$2 [NC,L]
Upvotes: 1
Reputation: 1312
Use this code for users.php script:
RewriteRule (.*) users.php?user=$1 [L,QSA]
This rule must be after messages rule in that order to work for both cases.
Upvotes: 1