htaccess pretty URL with PHP & URL variables - php

hoping someone can offer some assistance here. This is an issue with multiple layers. In short, I want to have pretty URLs that use a URL variable to a file within a folder.
So, I want http://www.example.com/?page=path/to/page to look like http://www.example.com/path/to/page/
On the index.php page, to load the above content:
require_once('content/'.$_GET['page'].'.php');
Current htaccess configuration:
RewriteEngine On
# Add trailing Slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ http://%{HTTP_HOST}/$1/ [L,R=301]
# Make URLs sexy!
RewriteRule ^([^/\.]+)/?$ index.php?page=$1 [L]
I can get this to work with a top level page within the /content folder, however, when the php file I with to include is within a folder inside the /content folder, it does not work.
Any ideas?? I believe the issue comes down to using an addition / in the ?page= variable. htaccess doesnt seem to like that.

After some playing, I figured it out. My regex was off.
Changed:
# Make URLs sexy!
RewriteRule ^([^/\.]+)/?$ index.php?page=$1 [L]
to:
RewriteRule ^(.*)(/)/?$ index.php?page=$1 [L]

Related

Removing trailing slash on custom urls with .htaccess (not wordpress)

I'm new to learning HTACCESS and I'm trying my best to work on a websites URLs to make them more "seo friendly" and load properly. I've tried searching all over for what I need to point me in the right direction, but everything seems to be for "wordpress" and this is a custom built site.
Here is my issue. This site had a previous developer, the thing was a mess, and I've spent countless hours cleaning up the site, and he built the sites to show urls like this. "www.sitename.com/about-us.php"
I'm familiar enough with htaccess to know how to remove the trailing extension for .php, even showing trailing variables properly that doesn't require the trailing slash at the end like: "sitename.com/about-us?contact=true"
I was able to get the blog view page to load with a url like this: "sitename.com/posts/post-name-here/". This one though does require the trailing slash.
What I'm trying to accomplish is making the url string to work properly with trailing variables for a few pages like, register, apply, etc. So those urls would be something like this. "sitename.com/auth/apply" or "sitename.com/auth/register"
My issue is that the urls have to have a trailing slash at the end or it doesn't load.
Plus adding a trailing variables only works when formatted like this: "sitename.com/auth/apply/?application=submitted"
I'd prefer it look more like this. "sitename.com/auth/apply?application=submitted", without the trailing slash. But I can't find how to accomplish this.
Here is my .htaccess snippet.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^posts\/(.*)/$ /view-post.php?post=$1 [QSA,NC,L]
RewriteRule ^auth\/(.*)/$ /auth-action.php?action=$1 [QSA,NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Can someone help me, or point me in the right direction?
This should be what you're looking for.
#Options +FollowSymLinks
Options -Indexes
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*) index.php [QSA,NC,L]
Try using the following in your .htaccess. This will remove the trailing slash from your URLs.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=302,L]
Make sure you clear your cache before testing this. You'll notice that I've set R=302 instead of 301. This makes it a temporary redirect for testing purposes. If you're happy with the redirect then change it to 301 to make it permanent.

Mod-rewrite rules to manipulate query string

Okay. First, I know there are multiple answers to a question like this here at StackOverflow, but they only helped me part of the way.
Unfortunately a lot of the answers are very specific and only help on the case of the original asker.
So it would be nice if I could get an explanation that might also be extendable to other users' questions (and for myself if I need to use this in other pages). That said, my issue is the following:
I've been trying to use mod_rewrite to simplify my URLs to something easier for my users to type in the address bar.
So I've got to edit .htaccess to hide .php extensions externally and edited all the links on the code to follow.
The rewrite rules I have found to work are the following:
Options +FollowSymLinks -MultiViews
RewriteEngine On
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://localhost/website/$1 [R=301,L]
# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://localhost/website/$1 [R=301,L]
# Assume php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]
These only deal with external redirection, but for me I don't really think internal redirection was needed, since I'm fine with just writing the short form of the URLs.
No reason hiding the extension if you just add them back in the html forms, right?
I draw users pages by receiving the username through the GET method.
www.webpage.com/userpage.php?view=username
What I want is the URL to become
www.webpage.com/user/username
When I finally got a rule that worked for this, the CSS file wasn't loading. Images could load or not depending on the rule I was using.
I scrapped the one I wrote because it was not only doing that but also were adding paths elsewhere.
RewriteRule ^(.*[^/]) userpage.php?view=$1 [QSA,L]
Basically this rule was applying '/userpage/' to all the links on the domain, regardless of what I typed in the address bar.
And when I typed the complete to it with the userpage.php it rewrote that to userpage/userpage/user.
RewriteRule ^user/(\w+)/?$ userpage.php?view=$1
Was very similar, did the same results, but wasn't showing images either.
I know that the problem here is with relative paths, but just changing all the paths to absolute will remove all the portability from the code.
I understand that what I really need here is to make it so ONLY pages with /user/ in the path to be rewritten.
I not only would like to understand what kind of conditionals do I need to apply to the rule only change what I want, and not everything else, but I would really love if someone could tell-me if there is a way for the page to be inaccessible through the full path.
E.g. www.fullpath.com/user/username display the page, but www.fullpath.com/userpage?view=username be inaccessible.
Keep your .htaccess like this:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
## Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ $1 [R=302,L,NE]
RewriteRule ^user/([^/]+)/?$ userpage.php?view=$1 [L,QSA,NC]
# To internally forward /dir/file to /dir/file.php
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]
Also add this in the <head> section of your page's HTML: <base href="/" /> so that every relative URL is resolved from that URL and not the current page's URL

Possible to link to CSS file despite htaccess redirect?

This question has been asked before, but the answers posted don't seem to work for me. I hoping for some troubleshooting.
I have an .htaccess file to redirect ALL requests to my index.php file, with the request path stored as a variable. I want, however, to exclude a single directory (/admin/assets) from this process so that I can easily link to css files, etc.
RewriteEngine On
RewriteBase /admin/
RewriteCond %{REQUEST_URI}!^(assets)
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
The above continues to redirect all traffic to the index.php file, but the linked-to CSS file (/admin/assets/main.css) is not loaded. What, if any, way is there around this?
Your %{REQUEST_URI} contains /admin/, even if you set the RewriteBase.
Plus, you missed a space in your RewriteCond.
You need tu use this .htaccess :
RewriteEngine On
RewriteBase /admin/
RewriteCond %{REQUEST_URI} !^/admin/assets
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Remove .PHP File Extension in URL

I am having a little issue forcing the .php file extension to be removed in the URL.
I am successfully able to remove .php file extension if user:
#Remove PHP if original request is /foo/bar.php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule ^(.*)\.php(\?.*)?$ $1$2 [R=301,L]
My goal is to get it also to remove the extension if:
# Remove PHP if original request is /foo.php/bar
I ask because right now a user can go to the URL and type http://www.site.com/contact.php/about and it will render my about page. My goal is force the removal of the .php and render:
http://www.site.com/contact/about
I was hoping to take the code I have above and add it to but I can not figure it out.
TIA
It looks like you got the removing part, but you're missing the internally rewriting part. What you have attempts to remove the php out of the URL and redirects the client to a URL without it. But your condition isn't matching requests, change it to:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ .*\.php.*$
RewriteRule ^(.*)\.php(.*)?$ /$1$2 [R=301,L]
Then you need to internally rewrite it back (don't redirect browser). So in the same htaccess file, add:
RewriteCond %{REQUEST_URI} ^/([^/]+)(.*)$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^([^/]+)(.*)$ /$1.php$2 [L]
the following .htaccess gives me the requested parameters, you can get "page"
AddDefaultCharset utf-8
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [L]
DirectoryIndex index.php
RewriteRule ^([a-zA-Z0-9_-]{3,20})/([^/]+)/([^/]+)?$ index\.php?page=$1&s=$2&o=$3 [L]
RewriteRule ^([a-zA-Z0-9_-]{3,20})/([^/]+)?$ index\.php?page=$1&s=$2 [L]
RewriteRule ^([a-zA-Z0-9_-]{3,20})/?$ index\.php?page=$1 [L]
RewriteRule ^([a-zA-Z0-9_-]{3,20})?$ index\.php?page=$1 [L]
ErrorDocument 404 /404
Get "page" parameter and then call it like this
include('inc/'.$_REQUEST['page'].'.php');
and remember to remove .php ext from your links
Replace your tow lines with this single one : (you have an error in your rule, that's why it is not detecting .php in the middle and you don't need the rewrite condition)
RewriteRule ^(.+)\.php(/.*)?$ /$1$2 [L,R=301]
My solution for these problems is to basically avoid using complex rewrite rules and do URL routing from the php side, via a simple front controller.
Write the following .htaccess file at the root of your website:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
Then write an index.php file in the same directory.
In the index.php file, you can still get the whole URL information, and choose a PHP file to include based on this.
<?php
// urldecode and get rid of the query string, $_GET is still available
$url = urldecode(preg_replace('/\\?(.*)$/', '', $_SERVER['REQUEST_URI']));
if ($url == '/contact/about') {
include 'contact.php';
}
That example is extremely basic, and I am probably ignoring subtleties of your website's architecture, but this approach is much more viable in the long run, because you can really map any URL of your liking to PHP scripts without having to endure the complexity of mod_rewrite.
This is the pattern that has been adopted by virtually every existing PHP framework (at least the MVC ones).
An minimalist example of this approach can be found in the Slim micro framework: http://www.slimframework.com/

.htaccess rewriting url to page or directory

For my site I have a RewriteRule that points the URL http://www.mysite.com/work to a work.php file. I also have a directory called "work" that has files in it, like project1.php, project2.php, etc...
What rules would I have to write so that the URL http://www.mysite.com/work knows to go to the work.php file, but the URL http://www.mysite.com/work/project1 knows I mean to go inside the directory "work" and display the project1.php file?
EDIT: Should point out, this is what I'm currently working with:
RewriteEngine On
RewriteBase /beta/
RewriteRule ^([a-z]+)$ $1.php [L]
Any additional tips to improve this security-wise? (Stopping directory jumping, etc...)
Try this:
RewriteEngin On
RewriteBase /
RewriteRule ^work$ /work.php [QSA,L]
That will ensure that http://www.mysite.com/work (no trailing slash) will go to your work.php file.
If you also want http://www.mysite.com/work/ (with trailing slash) to go work.php, add this line just above the last RewriteRule.
RewriteRule ^work/$ /work [R=301,QSA,L]
That will redirect it to the URL with no trailing slash thus, displaying the work.php file.
UPDATE: Since you already have a RewriteBase directive, just put the RewriteRule line(s) right after your RewriteBase but before your RewriteRule as the rule you're using a catch-all and will match everything.
This is the answer to your question. It works for me.
RewriteEngine On
RewriteBase /
RewriteRule ^([a-z]+)$ $1.php [L]
Simply remove beta/
Try this rule:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .* $0.php [L]

Categories