Mobile app version of vmapp.org
Login or Join
Si4351233

: Hiding and redirecting extensions on my webpage I want to hide extensions on my webpage using the .htaccess file. I have managed to do it by using this code; RewriteEngine On RewriteCond %{REQUEST_FILENAME}

@Si4351233

Posted in: #Htaccess #Php #UrlRewriting

I want to hide extensions on my webpage using the .htaccess file.

I have managed to do it by using this code;

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ .php [NC,L]


So when I visit mysite.com/index it shows my index.php. That's fine but I want to block visitors from visiting mysite.com/index.php so it should be redirected to mysite.com/index

I think I have found a way to do that. However, I will be using querystrings on my webpage. There will be some pages which I will need to carry the variables via GET method.

Normally a link with an id variable is like this;
index.php?id=xx

However, if I redirect /index.php to /index my variables will be gone. So I want the urls to seem like this when carrying a variable
mysite.com/index?id=xx

The extension will be PHP always. But I want this system work in all pages with all variables. I am not sure how many pages and variables there will be so do I have to write a rule in htacces for each of them or can I define a general rule? So it will be like this

Examples:
index.php?id=xx will be index?id=xx
index.php?page=xx will be index?page=xx
users.php?uid=xx will be users?uid=xx
news.php?nid=xx will be news?nid=xx


This could probably be achieved using .htaccess file but I don't know, how can I do that.

P.S. Although I am pretty good at PHP, I don't know anything about creating a rule for htaccess file I just use the codes I find on the internet.

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Si4351233

2 Comments

Sorted by latest first Latest Oldest Best

 

@BetL925

Based on this question you will need something like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)$ .php [NC,QSA,L,E=LOOP:1]

RewriteCond %{ENV:REDIRECT_LOOP} !1
RewriteRule ^(.*).php$ / [NC,QSA,R=301,L]


!-f and !-d ensure that it doesn't get executed for files and directories that exist

The environment variable LOOP is so that mod_rewrite doesn't try to redirect back to your friendly URLs from the rewritten URLs. It is read as REDIRECT_LOOP because mod_rewrite makes two passes over the rules and prepends REDIRECT_ to all environment variables the second time.

QSA is the "query string append" flag for rewrite rules that preserves your parameters

10% popularity Vote Up Vote Down


 

@Miguel251

Use that in root .htaccess:

RewriteEngine On
RewriteCond %{THE_REQUEST} s/+(.+).php[s?] [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)$ .php [NC,QSA,L]

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme