I’m trying to get the following functionality to work in PHP without a framework. I don’t want to have to worry about setting up a super complicated framework for every PHP application I do.
http://domain.com/sign_up.php
becomes
http://domain.com/sign_up/
http://domain.com/user.php?id=432
becomes
http://domain.com/user/?id=432
Or if there is a way to get that to become http://domain.com/user/432
but i’m not sure how to handle multiple $_GET
variables in that scenario so that’s optional.
This works pretty well so far:
RewriteRule ^sign_up/([^/]*)$ /sign_up.php?p=$1 [L]
The only problem is I have to do that for every single php file i’m using which can become a lot.
What is a universal way to do it for all php files?
UPDATES:
This one line is working perfectly:
RewriteRule ^(.*)/$ $1.php [NC]
Only issue is it doesn’t auto redirect PHP
For example, I want to 301 auto redirect:
http://domain.com/file.php
to
http://domain.com/file/
And
http://domain.com/file.php?var1=value&var2=value
to
http://domain.com/file/?var1=value&var2=value
If anyone can think of a better way to handle query string values in a more SEO friendly way that would be awesome! But otherwise this is working pretty great so far.
MORE UPDATES:
Now this is working:
http://domain.com/file/
– to –
http://domain.com/file.php
Both of those point to the same page with this htaccess code:
RewriteRule ^(.*)/$ $1.php [NC]
However http://domain.com/file
without the trailing /
returns a page not found error.
Also I need to know how to auto redirect http://domain.com/file.php
to http://domain.com/file/
MOSTLY WORKING HTACCESS
This .htaccess works beautifully:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !.(php|html?|jpg|gif)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
RewriteRule ^(.*)/$ $1.php [NC]
The only thing it doesn’t do is auto redirect if they go directly to http://domain.com/file.php
it does not redirect to http://domain.com/file/
but everything else about it is working.
3
Answers
Try this:
That’s because your rule does not match unless there’s a
/
at the end.You can make it optional with
?
asNote, that
/
does not need abefore it. It works with or without it.
If you get this working first, we can see what we can do about the query parameters later.
Your final htaccess could look like
You’ll probably want something like this:
The
[R=301]
appendixes redirect the browser to the new URL with a 301, moved permanently status header. That way the browser will know where to find the right url in the future, without asking the server.Also, sometimes an .htaccess checker is useful: http://htaccess.madewithlove.be/ Do note, the tool doesn’t work with
%{REQUEST_FILENAME}
.If you want
domain.com/help
to loaddomain.com/help.php
and still load all the jpg/png/css/img etc, use this: