Showing posts with label htaccess. Show all posts
Showing posts with label htaccess. Show all posts

Thursday, 20 September 2018

Aliasing images to a remote server with .htaccess

When maintaing a website for a customer where there are several gigabtyes of product images that change frequently, it can be annoying to have to keep a local copy of all those images, particularly when bandwidth usage is taken in to consideration. Using .hatccess files on Apache with a clever use of rewrite rules, it is possible to still reference the images files as if they are on the local webserver but they are really served off the remote server. This makes the local development copy of the website look just like the remote one without having to worry about keeping the images in sync. This post looks at how to do this.
mod_rewrite in the Apache web server allows you to rewrite URL requests to either a different local filename, or to a remote address either as a permanent or temporary redirection. Rewriting requests to local files is useful when running everything through a front end controller when using an MVC system, and to remote adress when redirecting from an old domain name to a new one. Remote rewrites are also useful for the above mentioned use where you want to rewrite local requests to a remote server.
Let's say for example that our product images are stored in /product_images/ under the publicly accessible part of the web root, and the remote website address is www.example.com. We could then add the following to the .htaccess file for this virtual host on our local development server:
RewriteEngine On
RewriteRule ^(product_images/.*) http://www.example.com/$1 [L]
The "RewriteEngine On" line switches on the rewrite engine.
The second line tells Apache to redirect all requests for URLs starting with product_images/ and followed by any sequence of characters to http://www.example.com/ and then to append the "product_images/" etc to the end. The [L] flag at the end tells the rewrite engine to stop processing any further rewrite rules that may come after this one.
This redirection process is transparent to the end user looking at the page in their browser as the images will show up as normal; it will just require a double request - 1st to the local server and 2nd to the remote - but for development purposes this is acceptable.
Checking the Apache log files you'll see something like this:
192.168.1.198 - - [14/Apr/2008:13:58:32 +1200] "GET /product_images/example.jpg HTTP/1.1" 302 343 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506)"
I have bolded the filename that was requested and the 302 response code. A 302 response code indicates a temporary redirect. In the example above, the web browser would first request the image file from the development server, get a 302 response and then request the image from http://www.example.com/product_images/example.jpg
You can add as many extra rules or modify the example above to include additional directories as required. For example, to do the above for both product_images and category_images you could do this:
RewriteEngine On
RewriteRule ^(product_images|category_images/.*) http://www.example.com/$1 [L]
This would then apply the rule for both directories.

Conclusion

It's very easy to add rewrite rules in Apache to serve image files from a remote address even when making the request locally as shown in the examples above. This can be very useful for developing or maintining a website because it means you don't need to be always synchronising your local images directory with those of the remote server.

Tuesday, 14 August 2018

Adding 301 Redirects using htaccess

It’s easy adding 301 redirects to your website using Apache’s htaccess. A 301 redirect is the most efficient and Search Engine Friendly method for web page redirection. It’s not difficult to implement and will preserve your search engine rankings as well.
Often when someone does a redesign of their website or puts it into a new platform, and little consideration is regarded for the difference between the existing an new link structure. You should have a redirect in place if your old link structure varies from the new one. This will help you maintain you search engine rankings and decrease the possibility if someone reaching a 404 page.
Below is one variant of a 301 that redirects when someone tries to access your website without the (www); It will redirect the URL to your website with the www. You should choose which variation your website should stick with because accessing your website both ways is bad for Search Engine Optimization.
So, to implement this type of redirect for your website, follow these instructions:
  1. Open up notepad or any other text editor and copy and paste the commands below.
  2. Change (yourdomain) to your domain name.
  3. Save the file with this name: (.htaccess). There is no file name.
  4. Upload it to the root directory of your website.

.htaccess – Limit website access by IP

I’ve been asked many times how to limit website access by allowable IP’s. This is fairly simple to accomplish with .htaccess and very useful for blocking web vagrants to allowing you to make updates to a website while redirecting all other IP’s to a maintenance page. Simply follow the steps below:
  1. Create a file and name it .htaccess.
  2. Add The following to the file:

     
  3. Replace 255.255.255.255 with you IP address. (If you don’t know it, you can get it here: WhatsMyIP)
  4. Once the file is created, put it in the root directory. That’s it!

How to Create a Custom 404 Error page with .htaccess


Everyone’s encountered those standard 404 error pages that yield little or no information. Most new systems have this feature built in by default and often times are pretty fancy with informative to funny graphics and lots of options on what to do next but, if your working on updating an old site not using dynamically based web pages then, your going to have to add one manually. For your user’s experience, it’s better to provide a helpful error message and links to where they can continue on their quest for information. You don’t want to scare your visitors away do you? Here’s how to add your own custom 404 error page to your website:
If you don’t already have an .htaccess file in your servers root, go ahead and create one. Now you need to instruct .htaccess where your custom error page is. In this example, I have the 404 document which I created with my editor that provides lots of useful information for users to continue browsing my site. Now add this line to your .htaccess file and that’s it!

Prepend and Append Files with .htaccess

One of the lessor known and used capabilities of .htaccess files is the ability to prepend and append includes to every page request. Doing so avoids needing to code 
<?php 
require('footer.php'); 
?> 
in every template file you wat to use them in. Here's the .htaccess code:
# Prepend the file 
php_value auto_prepend_file "/dir/path/utilities.php" 
 # Append file to bottom of page 
php_value auto_append_file "/dir/path/templates/footer.php"


Now don't mistake this post as me telling you to use this strategy; using this functionality creates a layer of indirection that could confuse a team of developers if they don't all have a grasp of where automatically included files are coming from. Just wanted to let you know this was possible!

Monday, 13 August 2018

Some .htaccess Rules To Improve PHP Portability

PHP is a powerful tool, but if you create any piece of software there are one or two things that you should never rely on.
A good example is using PHP short tags. This is a short hand way of stating that this block are to be parsed as PHP. This is an example of a normal tag.
 
Here is the same code using short tags.
 echo 'Hello World'; >
Another alternative, if you just want to print the output of a variable, is to use the following.
='Hello World'; >
The short tags setting can be turned on or off in the php.ini file. If you create an application that relies on these short tags then you will find that on some systems the short tags setting is turned off, which means that your software will simply not work.
You can force PHP to set this setting to on by using the following rule in your .htaccess file on a Apache server.
php_flag short_open_tag on
Note that this probably works with other servers that use .htaccess but I haven't been able to test it. Two other things that are useful to turn off are register globals and magic quotes.
  1. php_flag magic_quotes_gpc off
  2. php_flag register_globals off
The register_globals setting should be turned off on any server due to security reasons, but relying on magic quotes being turned on is equally as dangerous. As a rule you should always treat anything from the user as potentially dangerous, but turning this magic quotes off will allow you to be absolutely certain that your string is properly escaped. The problem comes when you escape a string and magic quotes is turned on. You tend to find your database input has multiple slashes.
PHP5 (when using certain functions) requires that you set your timezone, you can do this by using the following rule.
php_value date.timezone "UTC"
If you are testing your PHP code then you can use the following two rules to turn on error reporting and display errors.
  1. php_value error_reporting "8191"
  2. php_value display_errors "1"
To turn this off just change the display_errors setting to 0. You would want to do this on a production server!
Finally, one last little fix is to make sure that the server doesn't allow users to simple surf the contents of your directories. The following .htaccess rule will prevent Apache from showing the contents of a directory.
  1. # Security: Don't allow browsing of directories
  2. Options -Indexes
This is almost always turned off, but it is better to be safe and include it.

Sunday, 19 July 2015

htaccess: How to use htaccess

#301 Redirects for .htaccess
 
#Redirect a single page:
Redirect 301 /pagename.php http://www.domain.com/pagename.html
 
#Redirect an entire site:
Redirect 301 / http://www.domain.com/
 
#Redirect an entire site to a sub folder
Redirect 301 / http://www.domain.com/subfolder/
 
#Redirect a sub folder to another site
Redirect 301 /subfolder http://www.domain.com/
 
#This will redirect any file with the .html extension to use the same filename but use the .php extension instead.
RedirectMatch 301 (.*)\.html$ http://www.domain.com$1.php
 
##
#You can also perform 301 redirects using rewriting via .htaccess.
##
 
#Redirect from old domain to new domain
RewriteEngine on
RewriteBase /
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
 
#Redirect to www location
RewriteEngine on
RewriteBase /
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]
 
#Redirect to www location with subdirectory
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/directory/index.html [R=301,NC]
 
#Redirect from old domain to new domain with full path and query string:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*) http://www.newdomain.com%{REQUEST_URI} [R=302,NC]
 
#Redirect from old domain with subdirectory to new domain w/o subdirectory including full path and query string:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/subdirname/(.*)$
RewriteRule ^(.*) http://www.katcode.com/%1 [R=302,NC]
 
Rewrite and redirect URLs with query parameters (files placed in root directory)
 
Original URL:
 
http://www.example.com/index.php?id=1
Desired destination URL:
 
http://www.example.com/path-to-new-location/
.htaccess syntax:
 
RewriteEngine on
RewriteCond %{QUERY_STRING} id=1
RewriteRule ^index\.php$ /path-to-new-location/? [L,R=301]
Redirect URLs with query parameters (files placed in subdirectory)
 
Original URL:
 
http://www.example.com/sub-dir/index.php?id=1
Desired destination URL:
 
http://www.example.com/path-to-new-location/
.htaccess syntax:
 
RewriteEngine on
RewriteCond %{QUERY_STRING} id=1
RewriteRule ^sub-dir/index\.php$ /path-to-new-location/? [L,R=301]
Redirect one clean URL to a new clean URL
 
Original URL:
 
http://www.example.com/old-page/
Desired destination URL:
http://www.example.com/new-page/
.htaccess syntax:
 
RewriteEngine On
RewriteRule ^old-page/?$ $1/new-page$2 [R=301,L]
Rewrite and redirect URLs with query parameter to directory based structure, retaining query string in URL root level
 
Original URL:
 
http://www.example.com/index.php?id=100
Desired destination URL:
 
http://www.example.com/100/
.htaccess syntax:
 
RewriteEngine On
RewriteRule ^([^/d]+)/?$ index.php?id=$1 [QSA]
Rewrite URLs with query parameter to directory based structure, retaining query string parameter in URL subdirectory
 
Original URL:
http://www.example.com/index.php?category=fish
Desired destination URL:
http://www.example.com/category/fish/
.htaccess syntax:
 
RewriteEngine On
RewriteRule ^/?category/([^/d]+)/?$ index.php?category=$1 [L,QSA]
Domain change – redirect all incoming request from old to new domain (retain path)
 
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC]
RewriteRule ^(.*)$ http://www.example-new.com/$1 [R=301,L]
If you do not want to pass the path in the request to the new domain, change the last row to:
 
RewriteRule ^(.*)$ http://www.example-new.com/ [R=301,L]
 
#From blog.oldsite.com -> www.somewhere.com/blog/
retains path and query, and eliminates xtra blog path if domain is blog.oldsite.com/blog/
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI}/ blog
RewriteRule ^(.*) http://www.somewhere.com/%{REQUEST_URI} [R=302,NC]
RewriteRule ^(.*) http://www.somewhere.com/blog/%{REQUEST_URI} [R=302,NC]