SatbirSingh
SatbirSingh

Reputation: 198

How to add www in front of my wesite

I have a website say www.abcd.com. Its working fine if i access it using url http://abcd.com. But what i want is that if user go with url http://abcd.com, then web server should be able to convert it into url www.abcd.com.

%LOCATION_CONTAINS_HTACCESS_FILE% = Some Path

Some important changes in httpd.config are:

1. DocumentRoot "/var/www/html"


2. <Directory />
    Options FollowSymLinks
    AllowOverride All       #changed to All
</Directory>


3. <Directory "%LOCATION_CONTAINS_HTACCESS_FILE%">
    AllowOverride All
</Directory>


4. AccessFileName .htaccess                             #default
5. %LOCATION_CONTAINS_HTACCESS_FILE%/.htaccess           # I added 
6. <Files ~ "^\.ht">
    Order allow,deny
    Deny from all
</Files>

My .htaccess

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

With these changes I am getting error in line 5(from above, i think) when executing "service httpd restart":

Starting httpd: Syntax error on line 415 of /etc/httpd/conf/httpd.conf:
Invalid command '%LOCATION_CONTAINS_HTACCESS_FILE%/.htaccess', perhaps misspelled or defined by a module not included in the server configuration

I went through most of links on web, but couldn't get any specific solution to this.

I don't have much knowledge about Web services. But waiting for a simpler solution.

Hoping you guys have faced this issue & surely solved.

Upvotes: 1

Views: 83

Answers (1)

giorgio
giorgio

Reputation: 10202

I always use the snippet below:

RewriteEngine On
RewriteBase /

# Redirect non-canonical domains
RewriteCond %{HTTP_HOST}   !^www.yourdomain.com$ [NC]
RewriteRule ^(.*)$         http://www.yourdomain.com/$1 [L,R=301]

# Redirect non-www to www version
RewriteRule %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.]+\.[a-z]{2,6})$ [NC]
RewriteRule ^(.*)$       http://www.%1/$1      [R=301,L]

It does two things:

  1. The first snippet (below "Redirect non-canoncial domains") redirects visitors who come in from an alias (eg. my-domain-alias.com) to the main domain (yourdomain.com). It uses a 301 redirect (permanent) to let search engines know this is the right address (and not some duplicate content).
  2. It checks if the www prefix is used. If not, it redirects, and also redirects using the 301 status code.

Note: the NC flag tells apache to check ignoring the case.

-- Edit:

I'd change the order directive to:

# Protect hidden files from being viewed
<Files .*>
        Order Deny,Allow
        Deny From All
</Files>

This will deny access to ALL hidden files (eg. your php .user.ini file, if present), not only .htaccess/.htpasswd files etc.

Upvotes: 1

Related Questions