Score:0

nginx config for SEO friendly Laravel setup

kr flag

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.
Score:1
kr flag
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_ ...
    }
}
Paul avatar
cn flag
I was under the impression that trailing slash in nginx configs is to mitigate a security vulnerability?
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.