Detailed tutorial on using Drupal7 with Varnish and integrating the drupal module

Source: Internet
Author: User
Tags drupal drupal cache varnish
Varnish is a high-performance open-source HTTP accelerator that is relatively complex to use, especially when used with drupal. Now let's record the detailed settings for Drupal7 with Varnish. tutorial preparation environment first install a brand new Drupa... varnish is a high-performance open-source HTTP accelerator that is relatively complex to use, especially when used with drupal. Now let's record the detailed tutorial on how Drupal7 works with Varnish.

Prepare the environment

First, install a brand new Drupal. we recommend that you use drush to install Drupal quickly.

First, create a database and remember the user and password.

### Enter mysql
Mysql-uroot-p
Create database 'mydb' character set utf8 COLLATE utf8_general_ci;
Grant all on 'mydb'. * TO 'username' @ localhost identified by 'password ';
#### Exit mysql

Install Drupal7 using Drush:

Drush dl drupal-7.x; # -- select is used to select a version
Drush site-install standard -- account-name = admin -- account-pass = admin -- db-url = mysql: // YourMySQLUser: RandomPassword @ localhost/YourMySQLDatabase

The latest version of drupal7 is installed by default. to select a version, add the parameter-select.

After the installation is successful, download another varnish module.

# Go to the drupal Directory
Drush dl varnish

Install Varnish

The default CentOS is used as an example. because the Varnish version in the CentOS repository is earlier, you need to import a new repo. then, upgrade the yum software library.
For more information, see this link: https://www.varnish-cache.org/installation/redhat

####Varnish 4.0:rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-4.0.el6.rpmyum install varnish ####Varnish 3.0: ###RHEL 5 or a compatible distribution, use: rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-3.0.el5.rpmyum install varnish ###RHEL 6 and compatible distributions, use: rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-3.0.el6.rpmyum install varnish


# If the installed version is incorrect, update it.
# Yum update

Run the following command to check whether the installation is successful:

$ Usr/sbin/varnishd-V
Varnishd (varnish-3.0.5 revision 1a89b1f)
Copyright (c) 2006 Verdens Gang
Copyright (c) 2006-2011 Varnish Software

Set VCL of Varnish

Copy the following code to/etc/varnish/default. vcl:

backend default {  .host = "127.0.0.1";  .port = "80";} sub vcl_recv {  if (req.restarts == 0) {    if (req.http.x-forwarded-for) {      set req.http.X-Forwarded-For = req.http.X-Forwarded-For +  ", " +  client.ip;    }    else {      set req.http.X-Forwarded-For = client.ip;    }  }   # Do not cache these paths.  if (req.url ~ "^/status.php$" ||    req.url ~ "^/update.php$" ||    req.url ~ "^/ooyala/ping$" ||    req.url ~ "^/admin/build/features" ||    req.url ~ "^/info/.$" ||    req.url ~ "^/flag/.$" ||    req.url ~ "^./ajax/.$" ||    req.url ~ "^./ahah/.$") {    return (pass);  }   # Pipe these paths directly to Apache for streaming.  if (req.url ~ "^/admin/content/backup_migrate/export") {    return (pipe);  }   # Allow the backend to serve up stale content if it is responding slowly.  set req.grace = 6h;   # Use anonymous, cached pages if all backends are down.  if (!req.backend.healthy) {    unset req.http.Cookie;  }   # Always cache the following file types for all users.  if (req.url ~ "(?i).(png|gif|jpeg|jpg|ico|swf|css|js|html|htm)(?[wd=.-]+)?$") {    unset req.http.Cookie;  }   # Remove all cookies that Drupal doesn't need to know about. ANY remaining  # cookie will cause the request to pass-through to Apache. For the most part  # we always set the NO_CACHE cookie after any POST request, disabling the  # Varnish cache temporarily. The session cookie allows all authenticated users  # to pass through as long as they're logged in.  if (req.http.Cookie) {    set req.http.Cookie = ";" +  req.http.Cookie;    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|NO_CACHE)=", "; 1=");    set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");    set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");     # Remove the "has_js" cookie    set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");    # Remove the "Drupal.toolbar.collapsed" cookie    set req.http.Cookie = regsuball(req.http.Cookie, "Drupal.toolbar.collapsed=[^;]+(; )?", "");    # Remove AdminToolbar cookie for drupal6    set req.http.Cookie = regsuball(req.http.Cookie, "DrupalAdminToolbar=[^;]+(; )?", "");    # Remove any Google Analytics based cookies    set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");    # Remove the Quant Capital cookies (added by some plugin, all __qca)    set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");      if (req.http.Cookie == "") {      # If there are no remaining cookies, remove the cookie header. If there      # aren't any cookie headers, Varnish's default behavior will be to cache      # the page.      unset req.http.Cookie;      set req.http.X-Varnish-NoCookie = "TRUE";    }    else {      # If there is any cookies left (a session or NO_CACHE cookie), do not      # cache the page. Pass it on to Apache directly.      set req.http.X-Varnish-NoCookie = "FALSE";      set req.http.X-Varnish-CookieData = req.http.Cookie;      return (pass);    }  }   # Handle compression correctly. Different browsers send different  # "Accept-Encoding" headers, even though they mostly all support the same  # compression mechanisms. By consolidating these compression headers into  # a consistent format, we can reduce the size of the cache and get more hits.  # @see: http:// varnish.projects.linpro.no/wiki/FAQ/Compression  if (req.http.Accept-Encoding) {    if (req.http.Accept-Encoding ~ "gzip") {      # If the browser supports it, we'll use gzip.      set req.http.Accept-Encoding = "gzip";    }    else if (req.http.Accept-Encoding ~ "deflate") {      # Next, try deflate if it is supported.      set req.http.Accept-Encoding = "deflate";    }    else {      # Unknown algorithm. Remove it and send unencoded.      unset req.http.Accept-Encoding;    }  }   if (req.request != "GET" &&    req.request != "HEAD" &&    req.request != "PUT" &&    req.request != "POST" &&    req.request != "TRACE" &&    req.request != "OPTIONS" &&    req.request != "DELETE") {      /* Non-RFC2616 or CONNECT which is weird. */      return (pipe);  }  if (req.request != "GET" && req.request != "HEAD") {      /* We only deal with GET and HEAD by default */      return (pass);  }  ## Unset Authorization header if it has the correct details...  #if (req.http.Authorization == "Basic 
 
  ") {  #  unset req.http.Authorization;  #}  if (req.http.Authorization || req.http.Cookie) {      /* Not cacheable by default */      return (pass);  }   return (lookup);}  sub vcl_pipe {    # Note that only the first request to the backend will have    # X-Forwarded-For set.  If you use X-Forwarded-For and want to    # have it set for all requests, make sure to have:    set bereq.http.connection = "close";    # here.  It is not set by default as it might break some broken web    # applications, like IIS with NTLM authentication.} # Routine used to determine the cache key if storing/retrieving a cached page.sub vcl_hash {  if (req.http.X-Forwarded-Proto == "https") {    hash_data(req.http.X-Forwarded-Proto);  }} sub vcl_hit {  if (req.request == "PURGE") {    purge;    error 200 "Purged.";  }} sub vcl_miss {  if (req.request == "PURGE") {    purge;    error 200 "Purged.";  }} # Code determining what to do when serving items from the Apache servers.sub vcl_fetch {  set beresp.http.X-Varnish-CookieData = beresp.http.set-cookie;  # Don't allow static files to set cookies.  if (req.url ~ "(?i).(png|gif|jpeg|jpg|ico|swf|css|js)(?[a-z0-9]+)?$") {    # beresp == Back-end response from the web server.    unset beresp.http.set-cookie;  }  else if (beresp.http.Cache-Control) {    unset beresp.http.Expires;  }   if (beresp.status == 301) {    set beresp.ttl = 1h;    return(deliver);  }   ## Doesn't seem to work as expected  #if (beresp.status == 500) {  #  set beresp.saintmode = 10s;  #  return(restart);  #}   # Allow items to be stale if needed.  set beresp.grace = 1h;} # Set a header to track a cache HIT/MISS.sub vcl_deliver {  if (obj.hits > 0) {    set resp.http.X-Varnish-Cache = "HIT";  }  else {    set resp.http.X-Varnish-Cache = "MISS";  }} # In the event of an error, show friendlier messages.sub vcl_error {     set obj.http.Content-Type = "text/html; charset=utf-8";     set obj.http.Retry-After = "5";     synthetic {"
          
  "} + obj.status + " " + obj.response + {"           Error "} + obj.status + " " + obj.response + {"     
  

"} + obj.response + {"

Guru Meditation:

XID: "} + req.xid + {"

Varnish cache server

"}; return (deliver);}


After the configuration is complete, start Varnish.

Test results

Open the browser, enter the URL of druapl7, and check whether Drupal7 is normal, and then add the port number.
For example, our test address is: http://drupal7.phprm.com
Then use the browser to open varnish address, as follows: http://drupal7.phprm.com: 6081/

Test results. if both sides are normal, both drupal and varnish are normal.
Cache Drupal pages with Varnish

Use Firebug to view varnish requests. if you see the X-Varnish mark in the http header, it indicates that varnish has taken effect. in this case, we need to determine whether varnish has cached the page.
How to judge: X-Varnish is followed by a number indicating that it is not a cache. X-Varnish is followed by two numbers, indicating that the cache is successful.

Here, we will find that all varnish does not hit the cache, so the problem is... (The excavator will not appear)
How to make varnish cache take effect:

// Tell Drupal it's behind a proxy.$conf['reverse_proxy'] = TRUE; // Tell Drupal what addresses the proxy server(s) use.$conf['reverse_proxy_addresses'] = array('127.0.0.1'); // Bypass Drupal bootstrap for anonymous users so that Drupal sets max-age < 0.$conf['page_cache_invoke_hooks'] = FALSE; // Make sure that page cache is enabled.$conf['cache'] = 1;$conf['cache_lifetime'] = 0;$conf['page_cache_maximum_age'] = 21600;



Add the following content to the settings. php of Drupal, and refresh the browser. then you can see that the number of X-Varnish is changed to two (multiple clicks ).

So far, Varnish can completely cache Drupal pages. As shown in:



So what is the Varnish module of Drupal used?

Simply put, Varnish clears varnish cache through the Drupal cache interface, such as page expiration.
In addition, through the Expire module, you can precisely control those pages and control the Expiration Time, which is more convenient.

Configure the Varnish module of Drupal.org

Start the Varnish module, read the official description of the varnish module: https://www.drupal.org/project/varnish
Add the following two lines to the settings. php of Drupal:

// Add Varnish as the page cache handler.
$ Conf ['cache _ backends '] = array ('sites/all/modules/varnish. cache. Inc ');
$ Conf ['cache _ class_cache_page '] = 'varnishcache ';

Go to the Drupal settings page. The path is admin/config/development/varnish.

For example:
Varnish Control Terminal: 127.0.0.1: 6082
Varnish Control Key: 86b2d660-9768-4a13-ab90-4b0736d6a4d1
Click Save to change status to green.
(Note: Copy the value of the Control Key to the/etc/varnish/secret file)

After the setting is complete, clear the Drupal cache and you will find that the cache value in Varnish will be refreshed, achieving the goal of clearing the cache instantly.

++ To this complete ++ (more questions to drupal University: http://drupal001.net ask oh !) ++

Oh, another case is that Varnish is installed on another server, because Varnish controls the background to listen to the local machine by default. Therefore, if you want to refresh the cache of another reverse proxy server, you must modify the configuration. There are two optional methods,

First, let the Varnish Management backend address use the intranet IP address (such as 192.168.1.x). Generally, this architecture is an intranet cluster, so it is reasonable to listen to the intranet.
Second, the local machine uses autossh to map the local port 6082 to the intranet machine.

$ Autossh-fN-L 6082: localhost: 6082

Complete

So far, Drupal7 + Varnish configuration has been completed, and Drupal and varnish are also fully integrated. Varnish cache is always faster than other caches, so it can replace Boost cache.
If you want to use Varnish to cache dynamic content and have more content to do, this article will no longer increase your reading volume (^_^ ).

++

Finally, let's talk about Apache's RPAF Module.

Varnish uses X-Forwarded-For as the address information of the remote IP by default, but this is not a standard protocol, sometimes we still use $ _ SERVER ['remote _ ADDR '] in PHP to obtain the IP address.
Apache has a module. the configuration file RPAF. conf is as follows, and the correct IP address can be set. (Not much to mention)

RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1 192.168. 10.0.0.
RPAFheader X-Forwarded-

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.