Ansible template module for wordpress nginx vhost

In this post, I will share a simple playbook that run on localhost to demonstrate ansible template module with  nginx vhost for WordPress.


- name: run the playbook tasks on the localhost
  connection: local
  become: yes

    vhost_domain: ""


  - name: ensure aptitude is installed
    command: echo "Hello World"

  - name: Nginx wordpress vhosts
      src: "templates/wp-vhost.conf.j2"
      dest: "/etc/nginx/sites-enabled/{{ vhost_domain }}.conf"


server {
   listen 80;

   server_name www.{{ vhost_domain }} {{ vhost_domain }};
   root /var/www/{{ vhost_domain }};

   access_log /var/log/nginx/{{ vhost_domain }}.access.log;
   error_log /var/log/nginx/{{ vhost_domain }}.error.log;

   set $skip_cache 0;

   # POST requests and urls with a query string should always go to PHP
   if ($request_method = POST) {
	set $skip_cache 1;

   if ($query_string != "") {
	set $skip_cache 1;

   # Don't cache uris containing the following segments
   if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
   	set $skip_cache 1;

   # Don't use the cache for logged in users or recent commenters
   if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
   	set $skip_cache 1;

   index index.php;
   if ($host = 'www.{{ vhost_domain }}' ) {
       rewrite  ^/(.*)$  http://{{ vhost_domain }}/$1  permanent;

   location / {
       try_files $uri $uri/ /index.php?$args;

   location ~ \.php$ {
       fastcgi_index index.php;
       fastcgi_param           SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_param           HTTPS           off;
       fastcgi_pass            unix:/var/run/php/php7.1-fpm.sock;

       fastcgi_cache_bypass $skip_cache;
       fastcgi_no_cache $skip_cache;
       fastcgi_cache FASTCGICACHE;
       fastcgi_cache_valid 60m;
       add_header X-FastCGI-Cache $upstream_cache_status;

       fastcgi_buffer_size     16k;
       fastcgi_buffers         4 16k;
       fastcgi_split_path_info ^(.+\.php)(/.*)$;
       include                 fastcgi_params;
       fastcgi_param           SCRIPT_FILENAME $document_root$fastcgi_script_name;
       #fastcgi_param           HTTPS           off;

   location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
       expires max;
       log_not_found off;


Directory structure layout:

[email protected]:~/ansible-wp-vhosts# tree
├── playbook-wp-vhost.yml
└── templates
└── wp-vhost.conf.j2

How to run playbook:

ansible-playbook playbook-wp-vhost.yml

Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *