WordPress Config For Nginx PHP-FPM

Here’s how you can setup nginx and php-fpm for use with wordpress. It is assumed you have nginx and and php-fpm installed.

Requirements:

  • Domain mycooldomain1.com pointing to <server ip>
  • wordpress installed on /usr/share/mycooldomain1.com_wordpress
  • php-fpm listening on port 9000

Then on /etc/nginx/nginx.conf:

http {
  ...
  server {

    server_name mycooldomain1.com;
    access_log /var/log/nginx/mycooldomain1.com.access.log main;
    error_log /var/log/nginx/mycooldomain1.com.error.log;

    location / {
      root /usr/share/mycooldomain1.com_wordpress;
      index index.php index.html index.htm;
      
      # unless request is for a valid file, send it as a query to index.php
      # this will allow clean url (eg: mycooldomain1.com/hello/world)
      if(!-e $request_filename)
      {
        rewrite ^(.+)$ /index.php?q=$1 last;
      }
    }

    location ~ \.php$ {
      fastcgi_pass   localhost:9000;
      fastcgi_index  index.php;
      fastcgi_param  SCRIPT_FILENAME  /usr/share/mycooldomain1.com_wordpress;
      fastcgi_param  REQUEST_METHOD   $request_method;
      fastcgi_param  CONTENT_TYPE     $content_type;
      fastcgi_param  CONTENT_LENGTH   $content_length;
      include        fastcgi_params;
    }
  }
}

Restart both nginx and php-fpm once you’ve updated the config:

sudo service nginx restart
sudo service php-fpm restart
Advertisements

Nginx Virtual Host and Reverse Proxy

Firstly, there’s no such thing as Virtual Host in nginx. As the doc mentions, Virtual Host is an apache terminology.

Scenario:

  • Domain mycooldomain1.com pointing to VPS server
  • Nginx running on port 80
  • Tomcat running on port 8080
  • Only inbound TCP traffic to port 80 is allowed through firewall

In your nginx.conf (mine’s on /etc/nginx/nginx.conf), add following inside the http element:

http {
  ...
  server {

    server_name mycooldomain1.com;
    access_log /var/log/nginx/mycooldomain1.com.access.log main;
    error_log /var/log/nginx/mycooldomain1.com.error.log;

      location / {
        proxy_pass http://localhost:8080;
        proxy_redirect default;
        proxy_cookie_domain localhost mycooldomain1.com;
      }
  }
  ...
}

The server_name and location / expression matches request to http://mycooldomain.com while proxy_pass sets the backend where the response will be fetched from.

proxy_redirect ensures any 3xx redirects and Location: header on response is rewritten into mycooldomain1.com.