htaccess File redirecting and rewriting tutorial and tips

htaccess File redirecting and rewriting tutorial and tips

Jun 2, 2018 | Apache

Friendly/Pretty URLs help in search engine rankings

How to Create a .htaccess File?

One of the more powerful tricks of the .htaccess hacker is the ability to rewrite URLs. This enables us to do some mighty manipulations on our links; useful stuff like transforming Very Long URL’s into Short, Cute URLs, transforming dynamic ?generated=page&URL’s into /friendly/flat/links, redirect missing pages, preventing hot-linking, performing automatic language translation, and much, much more.

Make no mistake, mod_rewrite is complex. This isn’t the subject for a quick bite-size tech-snack, probably not even a week-end crash-course, I’ve seen guys pull off some real cute stuff with mod_rewrite, but with kudos-hat tipped firmly towards that bastard operator from hell, Ralf S. Engelschall, author of the magic module itself, I have to admit that a great deal of it still seems so much voodoo to me.

The way that rules can work one minute and then seem not to the next, how browser and other in-between network caches interact with rules and testing rules is often baffling, maddening. When I feel the need to bend my mind completely out of shape, I mess around with mod_rewrite!

After all this, it does work, and while I’m not planning on taking that week-end crash-course any time soon, I have picked up a few wee tricks myself, messing around with web servers and web sites, this place..

The plan here is to just drop some neat stuff, examples, things that have proven useful, and work on a variety of server setups; there are Apache’s all over my LAN, I keep coming across old .htaccess files stuffed with past rewriting experiments that either worked; and I add them to my list, or failed dismally; and I’m surprised that more often these days, I can see exactly why!

Very little here is my own invention. Even the bits I figured out myself were already well documented, I just hadn’t understood the documents, or couldn’t find them. Sometimes, just looking at the same thing from a different angle can make all the difference, so perhaps this humble stab at URL Rewriting might be of some use. I’m writing it for me, of course. but I do get some credit for this.

Disable directory Listing
# time to get dynamic, see..

RewriteRule (.*).htm $1.php

If you want to disable folder files listing, include following code.

# Disable Directory Browsing

Options All -Indexes

Error Pages
Here error page is redirecting to error.html.

	errorDocument 400 http://www.beingidea.info/error.html
	errorDocument 401 http://www.beingidea.info/error.html
	errorDocument 404 http://www.beingidea.info/error.html
	errorDocument 500 http://www.beingidea.info/error.html

beginning rewriting..

Whenever you use mod_rewrite (the part of Apache that does all this magic), you need to do..

you only need to do this once per .htaccess file:

	Options +FollowSymlinks
	RewriteEngine on

Old Domain Redirection
htaccess code for redirecting old domain(123web.com) to new domain(007web.com).

	RewriteCond %{HTTP_HOST} ^123web.com
	RewriteRule (.*) http://www.007web.com/$1 [R=301,L]
	RewriteCond %{HTTP_HOST} ^www.123web.com
	RewriteRule (.*) http://www.007web.com/$1 [R=301,L]

Hiding File Extension

	http://www.yourwebsite.com/index.html
	to
	
Home
RewriteRule ^([^/.]+)/?$ $1.html

Profile URL

Profile parameter allows [a-zA-Z0-9_-] these inputs. More help read Understanding Regular Expression

	http://beingidea.info/profile.php?username=beingamitverma
	to
	http://beingidea.info/beingamitverma
	RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1
	RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

Messages URL

http://beingidea.info/messages.php?message_username=amit
	to
	http://beingidea.info/messages/amit
	RewriteRule ^messages/([a-zA-Z0-9_-]+)$ messages.php?message_username=$1
	RewriteRule ^messages/([a-zA-Z0-9_-]+)/$ messages.php?message_username=$1

Friends URL

http://beingidea.info/friends.php?username=amit
	to
	http://beingidea.info/friends/amit
	RewriteRule ^friends/([a-zA-Z0-9_-]+)$ friends.php?username=$1
	RewriteRule ^friends/([a-zA-Z0-9_-]+)/$ friends.php?username=$1

not-so-simple rewriting … flat links and more:

You may have noticed, the above examples use regular expression to match variables. What that simply means is.. match the part inside (.+) and use it to construct “$1” in the new URL. In other words, (.+) = $1 you could have multiple (.+) parts and for each, mod_rewrite automatically creates a matching $1, $2, $3, etc, in your target (aka. ‘substitution’) URL. This facility enables us to do all sorts of tricks, and the most common of those, is the creation of “flat links”..

Even a cute short link like http://mysite/grab?file=my.zip is too ugly for some people, and nothing less than a true old-school solid domain/path/flat/link will do. Fortunately, mod_rewrite makes it easy to convert URLs with query strings and multiple variables into exactly this, something like..

a more complex rewrite rule:

Options +FollowSymlinks
	RewriteEngine on
	RewriteRule ^files/([^/]+)/([^/]+).zip /download.php?section=$1&file=$2 [NC]
	would allow you to present this link as..
	http://mysite/files/games/hoopy.zip

	and in the background have that transparently translated, server-side, to..

	
	http://mysite/download.php?section=games&file=hoopy

Multiple domains in one root:

If you are in the unfortunate position of having your sites living on a host that doesn’t support multiple domains, you may be forced to roll your own with .htaccess and mod_rewrite. So long as your physical directory structure is well thought-out, this is fairly simple to achieve.

For example, let’s say we have two domains, pointing at a single hosted root; domain-one.com and domain-two.com. In our web server root, we simply create a folder for each domain, perhaps one/, and two/ then in our main (root) .htaccess, rewrite all incoming requests, like this.

All requests NOT already rewritten into these folders, transparently rewrite.

 #two domains served from one root..

	
	    RewriteCond %{HTTP_HOST} domain-one.com
	    RewriteCond %{REQUEST_URI} !^/one
	    RewriteRule ^(.*)$ one/$1 [L]
	    RewriteCond %{HTTP_HOST} domain-two.com
	    RewriteCond %{REQUEST_URI} !^two
	    RewriteRule ^(.*)$ two/$1 [L]

All requests for the host domain-one.com are rewritten (not R=redirected) to the one/ directory, so long as they haven’t already been rewritten there (the second RewriteCond). Same story for domain-two.com. Note the inconsistency in the RewriteCond statement; !^/dir-name and !^dir-name should both work fine. But needless to say, if you get a 500 error on your server, that would be a good place to start looking!

Also note, with such a simple domain & folder naming scheme, you could easily merge these two rule sets together. This would be unlikely in the real world though, which is why I left them separate; but still, worth noting.

Other general settings and php directives can also go in this root .htaccess file, though if you have any further rewrite you’d like to perform; short URL’s, htm to php conversion and what-not; it’s probably easier and clearer to do those inside the sub-directory’s .htaccess files.

Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

0 Comments

Leave a Reply