0

I wasn't able to find an immediate solution to the 3rd item, below, so once I'd worked it out, I thought it would be helpful to post my general config for Laravel in order to help others searching for the same.

These settings would suit sysadmins seeking an SEO friendly Laravel setup. It isn't an exhaustive example; just a bare bones config to meet the requirements below. Fill in the remainder yourself.

How would one configure nginx for Laravel, in order to:

  1. Redirect all requests to serve a site at https://www.example.com?
  2. Access files directly, falling back to the central index.php controller?
  3. Strip index.php from requests which include it?
  4. Remove the trailing slash (/) from URIs.
HBruijn
  • 77,029
  • 24
  • 135
  • 201
zoot
  • 257
  • 1
  • 3
  • 13

1 Answers1

1
server {
    listen 1.2.3.4:80;
    server_name example.com www.example.com;
    location / {
        return 301 https://www.example.com$request_uri;
    }
}
server {
    listen 1.2.3.4:443;
    server_name example.com;

    ssl_ ...

    location / {
        return 301 https://www.example.com$request_uri;
    }
}
server {
    listen 1.2.3.4:443;
    server_name www.example.com;

    ssl_ ...

    root /path/to/doc/root;

    # redirect URIs with trailing / to ones without

    location ~ ^(.+)/$ {
        return 301 $1;
    }

    # strip index.php from requests
    # https://www.example.com/index.php/docs
    # becomes https://www.example.com/docs
    # likewise
    # https://www.example.com/index.php
    # becomes https://www.example.com

    if ($request_uri ~* "^/index\.php(/?)(.*)") {
        set $default 'https://www.example.com';
        return 301 "${default}/$2";
    }

    # attempt to serve files in-place,
    # or pass requests onto controller

    location / {
        try_files $uri $uri @controller;
    }

    location @controller {
        rewrite ^/(.*)$ /index.php?$query_string;
    }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_ ...
    }
}
zoot
  • 257
  • 1
  • 3
  • 13
  • I was under the impression that trailing slash in nginx configs is to mitigate a security vulnerability? – Paul Jul 10 '23 at 17:09