Mod-rewrite rules to manipulate query string - php

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

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.

Specific redirection in .htaccess does not work

I have a specific problem with my mod_rewrite configuration that I cannot resolve. I am no admin, therefore I'm kindly asking for a collective advice :) Please note - it's not a general question about redirection, but very specific one.
Story
I have a shared hosting with access to FTP and ability to create my own .htaccess files. This shared hosting had plenty of files and directories before I created the website, so logical step for me was to place everything inside new-site folder.
Then I had to create custom rewrite rules so that everything under example.com points to new-site.
CONFIG
So I came up with the following config.
# (...) other rules
# 1. Make sure that /new-site/ is not a duplicated content
RewriteCond %{REQUEST_URI} ^/new-site/
RewriteRule ^/new-site/(.*)$ /$1 [R=301,L]
# 2. Make sure that example.com is internally handled by files in '/new-site'
RewriteCond %{REQUEST_URI} !^/new-site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /new-site/$1
RESULTS
Rule marked with 2. works fine, my site is accessible as I want. However I didn't want https://example.com/new-site/ to be found on the server by bots and treated by a duplicated content, so I added rule 1..
This rule, however, doesn't seem to have any effect! I looked it up with CURL and request is handled immediately with a 200 status. I'm banging my head against the wall and experimenting with other variants of it, but everything fails.
What I'm after is pretty darn simple:
Make every request to the root domain be handled by website which is stored in /new-site/
Make sure that direct call to https://example.com/new-site/(.*) is redirected with 301 status back to the domain root.
What am I doing wrong?
EDIT
I've noticed that my setup seems to be doing far better if I remove a child .htaccess file under /new-site/ subfolder. I didn't mention it in my original question because there is nothing special about it (just some SEO rewrites).
RewriteEngine on
DirectoryIndex index.php
RewriteRule ^products$ products.php
# (...) similar rewrites
Old answer: RewriteRule does not accept leading slash. Try to change to
RewriteRule ^new-site/(.*)$ /$1 [R=301,L]
Edit:
Version that is provided by you will forward to the cyclic redirection. To avoid it, I think, you can use such .htaccess
RewriteEngine on
RewriteRule ^new-site/ - [R=404,L]
# 2. Make sure that example.com is internally handled by files in '/new-site'
RewriteCond %{REQUEST_URI} !^/new-site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /new-site/$1 [L]
Direct asking /new-site/* wil receive 404 error, while url exaple.com/* wil be redirected to /new-site
And notice that if there are files with the same name, for example, /r.jpg and /new-site/r.jpg, the last never be achieve
Your first rule never matches because it must not begin with a leading slash.
With RewriteRule, you only need a leading slash if you're directly in httpd.conf or before Apache v2.4 i think.
While you have a good idea, your first rule will cause an infinite redirection loop if it's working. You have to use THE_REQUEST to match direct user request only.
You can put this code in /.htaccess
# 1. Make sure that /new-site/ is not a duplicated content
RewriteCond %{THE_REQUEST} \s/new-site/([^\s]*)\s [NC]
RewriteRule ^ /%1 [R=301,L]
# 2. Make sure that example.com is internally handled by files in '/new-site'
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((?!new-site/).*)$ /new-site/$1 [L]
Also, you'll have to add this line in /new-site/.htaccess (to avoid automatic override)
RewriteOptions InheritBefore

URL mod_rewrite how to properly create syntax?

I have the following url:
http://example.com/files/101-info/index.php
My questions is:
Is it possible to remove the 101- in the url?
Is it possible to rewrite the name in the address bar, but keep the file in the current location?
I would like to make the file appear to be at:
http://example.com/files/info/index.php
but actually remain in:
/var/www/htdocs/files/101-info/index.php
Here's what I tried, but I couldn't remove the 101- and the redirect didn't work:
RewriteEngine On
RewriteRule ^([^/]+)/([0-9]+)-([^\/]+)/(.+)\.php$ /$1/$2/$4 [R] // also tried [NC,QSA]
NOTE: Keep in mind if you have other rules in your .htaccess that you have not mentioned in your question and you don't place the below rules at the proper place, it will not work as expected.
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+files/[0-9]+-([^/]+)/([^\s\?]+) [NC]
RewriteRule ^ /files/%1/%2 [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(files)/([^/]+)/([^/]+)$ /$1/101-$2/$3 [L]
First rule will remove the 101-, the 2nd rule will accept the 101- internally without having to change the folder name or the place your files are.
Change it from [R=302,L] to [R=301,L] once you confirm it is working.
Since you were previously using a redirect, your browser might be cached, so clear you cache and make sure to test the URL with a different browser until the cache of yours is cleared as it doesn't always happen after deleting it.

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/

Having trouble with a simple .htaccess redirect

I've been working on this for a while and have tried a lot of different solutions I've seen on the web and can't seem to get this to work.
I have a site at www.mydomainname.com. The page that I want to handle ALL page requests is www.mydomain.com/index.php. I'd also like to set this up to work for any other domains that I point to this code base (using wildcards would be the way to go for that I think).
So the following URL types (or any other) should automatically go to index.php, while still keeping the original URL structure in the browser address bar:
www.mydomain.com/
mydomain.com/
www.mydomain.com/item/111
www.mydomain.com/item/itemname/anothervariable/value
www.mydomain.com/item/itemname/?variable=value
I'm using PHP 5 and a recent version of Apache with mod_rewrite enabled.
Thanks in advance for any help!
Simple:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !\.(jpg|gif|ico|png|bmp|css|js)$
RewriteRule .* index.php
You could use the follow RewriteRule
RewriteEngine On
RewriteRule ^(.*)$ /index.php?originalUrl=$1
Untested, but it should work. You will then also have the original URL available in the 'originalUrl' GET parameter for further parsing.
Include this once per .htaccess file:
Options +FollowSymlinks
RewriteEngine on
RewriteRule (.*) index.php
If you need the information from the matched URL you can modify your RewriteRule to match portions of the old URL or just include everything by using the variables $1 and so forth. If for instance you wanted to get the item number passed in quickly to index.php, you could use this rule:
RewriteRule item/(.*)$ index.php?item=$1

Categories