Simula il routing mod_rewrite di Apache

La funzionalità di base di Apache mod_rewrite può essere simulata tramite l'uso di uno script PHP a cui si fa riferimento in app.yaml che a sua volta caricherà lo script desiderato. Questo esempio simula il pattern PHP comune in cui prevede che la variabile $_GET['q'] contenga il percorso di richiesta.

Informazioni su mod_rewrite.php

Per abilitare la funzionalità mod_rewrite, l'applicazione deve includere mod_rewrite.php, ovvero lo script che viene richiamato per tutte le richieste alla tua applicazione per eseguire il routing delle richieste. Come descritto nei commenti, lo script verifica l'esistenza di script PHP a livello principale e li richiama, posizionando la parte del percorso di $_SERVER['REQUEST_URI'] nella variabile $_GET['q'].

<?php
/**
 * @file
 * Provide basic mod_rewrite like functionality.
 *
 * Pass through requests for root php files and forward all other requests to
 * index.php with $_GET['q'] equal to path. The following are examples that
 * demonstrate how a request using mod_rewrite.php will appear to a PHP script.
 *
 * - /install.php: install.php
 * - /update.php?op=info: update.php?op=info
 * - /foo/bar: index.php?q=/foo/bar
 * - /: index.php?q=/
 */

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Provide mod_rewrite like functionality. If a php file in the root directory
// is explicitly requested then load the file, otherwise load index.php and
// set get variable 'q' to $_SERVER['REQUEST_URI'].
if (dirname($path) == '/' && pathinfo($path, PATHINFO_EXTENSION) == 'php') {
  $file = pathinfo($path, PATHINFO_BASENAME);
}
else {
  $file = 'index.php';

  // Provide mod_rewrite like functionality by using the path which excludes
  // any other part of the request query (ie. ignores ?foo=bar).
  $_GET['q'] = $path;
}

// Override the script name to simulate the behavior without mod_rewrite.php.
// Ensure that $_SERVER['SCRIPT_NAME'] always begins with a / to be consistent
// with HTTP request and the value that is normally provided.
$_SERVER['SCRIPT_NAME'] = '/' . $file;
require $file;

Esempio di app

Di seguito è riportata un'applicazione molto semplice, scritta in modo da prevedere $_GET['q'].

app.yaml

Come puoi vedere da questo file app.yaml, questa applicazione fornisce due script PHP a livello di directory principale e pubblica file statici da una directory denominata downloads.

application: mod_rewrite_simulator
version: 1
runtime: php55
api_version: 1

handlers:
# Example of handler which should be placed above the catch-all handler.
- url: /downloads
  static_dir: downloads

# Catch all unhandled requests and pass to mod_rewrite.php which will simulate
# mod_rewrite by forwarding the requests to index.php?q=... (or other root-level
# PHP file if specified in incoming URL.
- url: /.*
  script: mod_rewrite.php

index.php

index.php è un index.php in stile router che legge $_GET['q'] per determinare il percorso di richiesta.

<?php

if ($_GET['q'] == '/help') {
  echo 'This is some help text.';
  exit;
}

echo 'Welcome to the site!';

other.php

Di seguito è riportato un esempio di script di livello principale che può essere chiamato direttamente. Molti framework PHP hanno script come install.php o update.php che si comportano in modo simile.

<?php

echo 'Welcome to the other site.';

Richieste di esempio

Data l'applicazione di esempio sopra riportata, le seguenti richieste verrebbero gestite come mostrato.

  • / si traduce in index.php con $_GET['q'] = '/'
  • /help si traduce in index.php con $_GET['q'] = '/help'
  • /other.php si traduce in other.php con $_GET['q'] = null
  • /downloads/foo_17.png si traduce in downloads/foo_17.png

Evita di dover usare mod_rewrite.php

Molti framework PHP non dipendono più da $_GET['q']. Utilizzano invece $_SERVER['REQUEST_URI'], che funziona sia con che senza mod_rewrite. Di conseguenza, quest'ultimo è il metodo preferito su App Engine.

Come utilizzato in mod_rewrite.php, un metodo pulito per utilizzare REQUEST_URI è il seguente:

<?php

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if ($path == '/help') {
  echo 'This is some help text.';
  exit;
}

echo 'Welcome to the site!';