Pretty WordPress-style URLs with Nginx and PHP

Recently, I was working on a project that needed to have pretty WordPress-style (and arguably more SEO-friendly) links for a CMS system.

This particular CMS has 3 types of pages: section, subsection and page, so the desired URL would always be in one of the following 3 forms:

  • http://domain/section
  • http://domain/section/subsection
  • http://domain/section/subsection/page

I made this work by sending all client requests (regardless of URL) to a single PHP page that split the URL into components used for fetching the real data (either from a file via a require, a database, or some other place).

The relevant nginx configuration code is nice and simple:

location / {
   try_files       $uri    /index.php;
}

The URI is parsed by the following PHP code:

// exit if we find any funny characters in URI
if (preg_match('/[^\w\-\/]/', $_SERVER['REQUEST_URI'])) {
    header('Location: /');
    exit;
}

// split the URI into elements
$a_uri = array_filter(explode('/', $_SERVER['REQUEST_URI']));

// ternary operations to assign string, or empty string
$section        = (!empty($a_uri)) ? array_shift($a_uri) : '';
$subsection     = (!empty($a_uri)) ? array_shift($a_uri) : '';
$page           = (!empty($a_uri)) ? array_shift($a_uri) : '';

Once this combination of 3 variables is available, I can use it to get hold of the content and send it to the client.