Nginx – Elastic Beanstalk Custom Nginx conf

elastic-beanstalknginxPHP

I'm setting up a new Amazon Linux 2/PHP/NGINX environment and I'm a little unfamiliar with Nginx since my last environment on Elastic Beanstalk was Amazon Linux/PHP/Apache. (Amazon changed the proxy to Nginx from Apache and the underlying platform was upgraded from Amazon linux to AL2)

Previously, I had an .htaccess file to handle multiple domains where a domain would have a corresponding folder that it would be served from. But, I know that .htaccess file won't work with Nginx.

So far I've tried adding a config file to the .ebextensions folder with something like this:

files:
  "/etc/nginx/sites-available/example.com.conf":
    mode: "000644"
    owner: root
    group: root
    source: https://someothersite.com/example.com.conf

The source being referenced (example.com.conf) contains this:

server {
        listen 80;
        root /var/www/html/example.com;
        index index.html index.php;
        server_name example.com;
   location / {
       try_files $uri $uri/ =404;
   }
}

I thought I needed to create a symbolic link, so I have another config file in the .ebextensions folder that contains this:

commands:
  10_link:
    command: sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com

After this ln command, I get an error during build. If I don't do that command I don't get an error, but it doesn't work (example.com/test.php wouldn't be served)

My last attempt was to do nothing in the .ebextensions folder and I created .platform/nginx/conf.d/custom.conf with the contents of

server {
            listen 80;
            root /var/www/html/example.com;
            index index.html index.php;
            server_name example.com;
       location / {
           try_files $uri $uri/ =404;
       }
    }

This seems to be closer as example.com/test.php is going to the file, but the server is prompting the browser to download the php file instead.

Best Answer

  1. For test purposes you can simply create files inside the /etc/nginx/sites-enabled folder

  2. For multiple domains you can use

    server_name *.domain1.com custom.domain2.com;

  3. Lastly, we need to process all PHP files via the FastCGI(on Ubuntu you can install it apt-get install php7.0-fpm) interface to PHP-FPM.

    server {
    listen       80;
    
    server_name  mydomain.com; 
    
    access_log  /var/log/nginx/access.log  combined; 
    location / { 
        root   /var/www/html; 
        try_files $uri $uri/ /index.php?$args;     
    } 
    location ~ \.php$ { 
        fastcgi_pass unix:/var/run/php7.0-fpm.sock; 
        fastcgi_index index.php; 
        fastcgi_param SCRIPT_FILENAME 
         $document_root$fastcgi_script_name; 
        include fastcgi_params; 
    } }