Include and Version NGINX Configs in Laravel Forge

• 1 min read

Most of my projects are hosted on servers provisioned by Laravel Forge. Forge provisions all servers with NGINX and after creating a site, also allows you to edit the NGINX config per site through their web interface.

The web editor is great, but I like to keep all important settings and files of a project in Git. NGINX has an include-directive, which allows us to import any file into a configuration block.

As an example, I've extracted the logic to add HTTP headers into a file called include.headers and stored the file in the root of my project.

add_header X-Frame-Options "DENY";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "no-referrer-when-downgrade";

Let's say my site is called "example.org". After my changes have been deployed, the file would be located at /home/forge/example.org/include.headers on the server.

NGINX doesn't automatically load our include.headers-file. We have to add the mentioned include-directive to the NGINX config of the site. In Forge, go to your site and open the NGINX configuration editor and add the following line.

include /home/forge/example.org/include.headers;

For my "example.org" site, the configuration would look like this.

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.org;
    root /home/forge/example.org;

    # Use absolute paths to load your include-files
    include /home/forge/example.org/include.headers;

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DOT NOT REMOVE!)
    include forge-conf/example.org/server/*;
}

You can of course can also place location-blocks into your includes-files. Maybe you want to add long expire headers to all CSS, JS, font and image-files?

location ~* \.(ico|css|js|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
    expires 90d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

Just keep in mind, that the overall NGINX configuration of your site and server has to be valid. If you commit a typo in your includes-file, your whole server might come down.