For those of you getting into the “nuts and bolts” of website design, you will find that there are times where you will need to create and/or modify the .htaccess file. In this regard, I have provided some of the most important .htaccess scripts I have come across, many which I use and have found indispensable.
If you are unfamiliar with .htaccess creation, all you need is “notepad” (not msword) since you want to ensure that there is no default character formatting. You add the code you wish into it, and then upload the file titled .htaccess to your public folder where the html files are stored (typically called public_html, or www, etc). In some cases there will be unique .htaccess files for the different folders, especially useful if you wish to block access to some folders and their files, but not all. Ok, that being said, here they are:
1. HTACCESS for Mobile Redirect and Back
I have done a lot of searching for this one. There are lots of scripts that will work to detect the device platform, so it is easy to detect if one is on a mobile device, and then redirect them to the mobile site version. The difficult part was finding one that would allow a person to return back to the main website (upon clicking a link) since the redirect would “loop” back to the mobile. From what I read, most recommend using cookies and sessions for this, but after numerous failed attempts I decided against this (especially since many people have cookies disabled). You will also note that there are PHP scripts that provide this functionality, but in this case your home page would need the .php extension (which I didn’t want), and their are supposedly javascript options, but few have had success with these.
I did finally find code that worked well, and it is use on my website. This code will check if you are using a mobile device, and where you’ve come from (google, etc), and if you are using a mobile device you are directed to the mobile site. Note that most mobile websites are created as sub-domains called “m”. So, my site, which is ecurtisdesigns.com, has a mobile version called m.ecurtisdesigns.com. The script following will redirect one to the m. version (sub-domain) of the primary domain, yet … and here is the good part … if you click a link back to the original site it won’t loop, instead it reads that you are currently on the mobile site, and will allow you back to the original. So long as you stay on the original you will view the non-mobile site pages. If you close the browser window, and then visit the site again, yep, you go back to the mobile because in this case you were not on the mobile version. Great stuff!
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} “text/vnd.wap.wml|application/vnd.wap.xhtml+xml” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “wapp|wapr|webc|winw|winw|xda|xda-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “up.browser|up.link|windowssce|iemobile|mini|mmp” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “symbian|midp|wap|phone|pocket|mobile|pda|psp” [NC]
#————- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$
#————-
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteCond %{HTTP_REFERER} !^https://(.*).yourmaindomain.com/.*$ [NC]
RewriteRule ^(.*)$ /m/ [L,R=302]
A final note, the iPad was excluded (though many redirect scripts include it) since it has a larger screen than other mobile devices so can view a regular website without much trouble. The line “RewriteCond %{HTTP_REFERER} !^https://(.*).yourmaindomain.com/.*$ [NC] ” is what allows the mobile site visitor to return to the main website.
2. Custom Error Page
By default your browser will serve up an error page in those cases where a page link is broken, or someone manually enters a link to a page that does not exist. The best solution is to create a custom page since this will allow you to track errors (if you wish), and you now have the opportunity to brand the page creatively, have it match your existing website, … and what most will do is provide a site-map, search engine, etc. to help someone find content on your site that you know does exist. You could create the page as a .html, but if you wish to track which pages are not being found (though Google Webmaster tools will do this for you as well), all you do is create an normal html page, and then save it as a .php page and add a bit of code into it.
< ?php
$ip = getenv (“REMOTE_ADDR”);
$requri = getenv (“REQUEST_URI”);
$servname = getenv (“SERVER_NAME”);
$combine = $ip . ” tried to load ” . $servname . $requri ;
$httpref = getenv (“HTTP_REFERER”);
$httpagent = getenv (“HTTP_USER_AGENT”);
$today = date(“D M j Y g:i:s a T”);
$message = “$today n
$combine n
User Agent = $httpagent n
$note n
$httpref “;
$message2 = “$today n
$combine n
User Agent = $httpagent n
$note n
$httpref “;
$to = “name@youremail.com”;
$subject = “Email Title of Error Page”;
$from = “From: name@youremail.comrn”;
mail($to, $subject, $message2, $from);
echo $message;
?>
As you can see in the code above, it will send you an email when a page is not found (nice to find broken links on your site), and it will tell you the server name, IP address, referer, date it was accessed, page name of error, etc. I have noted that most of my page errors come from bots that have stored previous versions of site pages that have had the names changed, and hackers who are trying to break into directories (more on this next).
Here is an example of the email notice I received when a bot tried to access a page that no longer exists:
208.115.113.83 tried to load www.ecurtisdesigns.com/zencart/index.php?main_page=contact_us
User Agent = Mozilla/5.0 (compatible; Ezooms/1.0; ezooms.bot@gmail.com)
Ok, so now for the .htaccess file, you add “ErrorDocument 404 /404NameOfPage.php” to the file. “404” is the name of the error handling, so it is a good idea to keep this in the file name for the sake of recognition. The actual code I use for my page is: ErrorDocument 404 /404NotFound.php
3. Selective Access Blocking
Ok, so I noted above that hackers will spend their nights trying to break into your directories. Mine are very secure, but just the same I will block an IP address of one that is seeking to access my configuration files. In this case you simply add the following to the .htaccess file.
order allow,deny
deny from 174.133.99.3
deny from 202.28.37.63
allow from all
As you can see, this is very simple. You have “order allow,deny” followed by the “deny from … with the IP address of the miscreants. Then you finish with “all from all”.
4. Force a Trailing Slash on URL
Some feel that it is best to always have a trailing slash on the primary URL since this encourages the search engines to explore deeper. It may, not sure. If this is important to you, yes, there is an .htaccess code snippet for this:
RewriteCond %{REQUEST_URI} /+[^.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
5. Disable Hotlinking
Websites which have a gallery of images will often find their bandwidth slowing down as a result of hotlinking. Hotlinking occurs when someone links directly to an image on your site, instead of a remote image on their own local server. The .htaccess code to prevent this is:
RewriteEngine On
#Replace ?mysite.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^https://(.+.)?mysite.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your “don’t hotlink” image url
RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]
6. HTACCESS Fast Caching
For websites that have lots of images, video, and flash, it is a good idea to speed up your site’s page load by caching images and other memory intensive files. This code will override one’s own cache settings, … the only potential downside is if you change your content often a visitor may not see your new content until they refresh the page a couple of times though as you can see, the cache time varies by type of file, so it should meet the needs of most.
#1 year
<FilesMatch “.(ico|pdf|flv)$”> Header set Cache-Control “max-age=29030400, public” </FilesMatch>
# 1 WEEK
<FilesMatch “.(jpg|jpeg|png|gif|swf)$”> Header set Cache-Control “max-age=604800, public” </FilesMatch>
# 2 DAYS
<FilesMatch “.(xml|txt|css|js)$”> Header set Cache-Control “max-age=172800, proxy-revalidate” </FilesMatch>
# 1 MIN
<FilesMatch “.(html|htm|php)$”> Header set Cache-Control “max-age=60, private, proxy-revalidate” </FilesMatch>
7. Stop Spammers on WordPress
For those of you who have blogs, yet don’t use askimet (I don’t since only the non-commercial version is free), here is some code that will help keep the spam to a minimum. What it does is prevent spam bots directly access to your wp-comments-post.php file (used to post comments on your blog). Of course some will simply visit your blog site and manually spam, … yeah!
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^https://%{REMOTE_ADDR}/$ [R=301,L]
8. Logging PHP Errors
It is a good idea to hide PHP errors from visitors since hackers will often use the errors to perform a process of elimination when trying to access a vulnerability in dynamic php pages. this code will do that.
# display no errors to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log
9. Wp-config Added Protection
The wp-config file is the WordPress configuration file that links up to the server. As a general rule you will make the file non-writeable through CHMOD settings after installation (and delete the install directory which writes to this file), but it is also a good idea to secure it even more by adding the following code into your .htaccess file.
order allow,deny deny from all
10. Disable Directory Browsing
I often come across websites where the directory is accessible. This allows me to open up every folder, and browse for whatever I want. An easy way to prevent this is to the add the following to your .htaccess file.
# disable directory browsing Options All -Indexes
Well, that’s it for this one, will add more as time allows!
HTACCESS for Mobile Redirect and Back question. Not a programmer, so have no clue what code means.
If instead of redirecting to a subdomain like in your example from https://yourdomain.com to https://m.yourdomain.com, how do you make it work with 2 separate domain names? Absolute urls?
What I want to do is redirect from desktop site with domain https://virtualmarcom.com to mobile site with https://virtualmarcom.mobi and allow link back to desktop site https://virtualmarcom.com without redirect. Only changes needed in lines below? What would they be? Also, does it require RewriteEngine Off in .htaccess file for https://virtualmarcom.mobi? Anything else?
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_REFERER} !^https://(.*).yourmaindomain.com/.*$ [NC]
RewriteRule ^(.*)$ /m/ [L,R=302]
Hello Eric. The rewrite rule is what you need to focus on. Note at the bottom which reads: RewriteRule ^(.*)$ /m/ [L,R=302]
Being new to .htaccess, I would suggest reading up a bit. There are a lot of websites that explain htaccess mod rewrites. For example:
RewriteEngine On
Redirect 301 https://www.nonmobilesite.com https://www.newmobilesite.com
This provides a permanent redirect from one url to another.
Ok, so for the above “M” subdomain rewrite, to link to another URL instead independent of your existing website, you would have:
RewriteRule ^(.*)$ https://www.mobilewebsite.com [L,R=302]
You could also link to a folder in the new website such as:
RewriteRule ^(.*)$ https://www.otherwebsitewebsite.com/mobile/mobile.html [L,R=302]
Edmund–
Thanks for your response.
Permanent 301 is not what I want. That’s easy enough. It’s the allowing the user back to the desktop version of the site if they so choose. Common client request lately. My client’s desktop/iPad site is nicholsonvineyards.com and the mobile site is nicholsonvineyards.mobi. Two completely different websites and not a subdomain.
So I made only this change to the last line:
RewriteRule ^(.*)$ https://www.nicholsonvineyards.mobi [L,R=302]
And it doesn’t redirect to the mobile site unless you reload the browser on my iPhone. Then it redirects to https://www.nicholsonvineyards.mobi after reload.
2nd line:
RewriteCond %{REQUEST_URI} !^/m/.*$
and
2nd to last line:
RewriteCond %{HTTP_REFERER} !^https://(.*).yourmaindomain.com/.*$ [NC]
Don’t these lines need changes?
Below is .htaccess file I have now at nicholsonvineyards.com. No instructions on .htaccess file at nicholsonvineyards.mobi for RewriteEngine on or off.
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} “text/vnd.wap.wml|application/vnd.wap.xhtml+xml” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “wapp|wapr|webc|winw|winw|xda|xda-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “up.browser|up.link|windowssce|iemobile|mini|mmp” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “symbian|midp|wap|phone|pocket|mobile|pda|psp” [NC]
#————- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$
#————-
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteCond %{HTTP_REFERER} !^https://(.*).yourmaindomain.com/.*$ [NC]
RewriteRule ^(.*)$ https://www.nicholsonvineyards.mobi [L,R=302]
Edmund–
Thanks for your response.
Got the redirect to work, but the back to full website link doesn’t work. Did some guesswork on lines 2 and 15 with the domains. I’m lost at this point. Here’s what I have right now at nicholsonvineyards.com .htaccess file (see below). Tried it with RewriteEngine Off in nicholsonvineyards.mobi .htaccess file but still didn’t work.
Maybe I’m not understanding something basic like .htaccess only works for parent directory and all subdirectories and not from one domain to another???
RewriteEngine On
RewriteCond %{REQUEST_URI} !^https://www.nicholsonvineyards.mobi.*$
RewriteCond %{HTTP_ACCEPT} “text/vnd.wap.wml|application/vnd.wap.xhtml+xml” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “wapp|wapr|webc|winw|winw|xda|xda-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “up.browser|up.link|windowssce|iemobile|mini|mmp” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “symbian|midp|wap|phone|pocket|mobile|pda|psp” [NC]
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteCond %{HTTP_REFERER} !^https://www.nicholsonvineyards.com/.*$ [NC]
RewriteRule ^(.*)$ https://www.nicholsonvineyards.mobi [L,R=302]
Hi Eric. Sorry you’re still having trouble. I do understand the frustration, I spent a couple of weeks looking for a solution that would actually work for me. It may be that the redirect loop will continue unless the domain is a subdomain, but I imagine that the code can be edited to allow for this.
One resource I used, which has an active community for help is https://ohryan.ca/blog/2011/01/21/modern-mobile-redirect-using-htaccess/ There code is a bit different from what I used, which was a mix of different things I had found online, but I would suggest starting here for answers. If they can’t help, just look for “htacess mobile redirect no loop”, and you will likely find what you need.
OK. Thanks for your help.