Reescriba todas las solicitudes a index.php con nginx


En mi configuración de apache tengo la siguiente regla de reescritura simple que

  1. a menos que el archivo exista, se reescribirá a index.php
  2. en las urls nunca se ve la extensión de archivo (.php)

¿Cómo puedo reescribir esto en nginx?

#
# Redirect all to index.php
#
RewriteEngine On

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} (/[^.]*|\.)$ [NC]
RewriteRule .* index.php [L]

Así es como mi bloque de servidor nginx se ve ahora, pero no funciona : (

root /home/user/www;
index index.php;

# Make site accessible from http://localhost/
server_name some-domain.dev;


###############################################################
# exclude /favicon.ico from logs
location = /favicon.ico {
    log_not_found off;
    access_log off;
}   

##############################################################
# Disable logging for robots.txt
location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}   

##############################################################
# Deny all attempts to access hidden files such as 
# .htaccess, .htpasswd, .DS_Store (Mac).
location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
}   

##############################################################
#   
location / { 
    include /etc/nginx/fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME  $document_root/index.php$args;
    fastcgi_pass    127.0.0.1:9000;
}   

###############################################################
# serve static files directly
location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
    access_log off;
    expires    30d;
}   

###############################################################
# redirect server error pages to the static page /50x.html
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root html;
}   

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#   
location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    # With php5-cgi alone:
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;
}
Author: ptheofan, 2012-10-17

8 answers

1 a menos que el archivo exista, se reescribirá a index.php

Añadir lo siguiente a su location ~ \.php$

try_files = $uri @missing;

Esto primero intentará servir el archivo y si no se encuentra se moverá a la parte @missing. así que también agregue lo siguiente a su configuración (fuera del bloque location), esto redirigirá a su página de índice

location @missing {
    rewrite ^ $scheme://$host/index.php permanent;
}

2 en las url nunca se ve la extensión de archivo (.php)

Para eliminar la extensión php lea el siguiente: http://www.nullis.net/weblog/2011/05/nginx-rewrite-remove-file-extension /

Y la configuración de ejemplo del enlace:

location / {
    set $page_to_view "/index.php";
    try_files $uri $uri/ @rewrites;
    root   /var/www/site;
    index  index.php index.html index.htm;
}

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/site$page_to_view;
}

# rewrites
location @rewrites {
    if ($uri ~* ^/([a-z]+)$) {
        set $page_to_view "/$1.php";
        rewrite ^/([a-z]+)$ /$1.php last;
    }
}
 31
Author: jagsler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-17 16:43:14

Solución perfecta Lo he intentado y tengo éxito para obtener mi página de índice cuando he añadido este código en el archivo de configuración de mi sitio.

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

En el propio archivo de configuración explicó que en "Primer intento de servir a la solicitud como archivo, luego como directorio, luego volver al índice.html en mi caso es index.php como estoy proporcionando página a través de código php.

 94
Author: Sanju D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-13 07:49:04

Para pasar las variables get también use $args:

location / {
    try_files $uri $uri/ /index.php?$args;
}
 51
Author: Jan Wy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-12 15:15:16

La configuración plana y simple sin reescribir, puede funcionar en algunos casos:

location / {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /home/webuser/site/index.php;
}
 15
Author: iutinvg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-06 11:41:30

Usando nginx is is_args en lugar de ? Para OBTENER cadenas de consulta

location / { try_files $uri $uri/ /index.php$is_args$args; }
 2
Author: razzbee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 18:11:01

Esto es lo que funcionó para mí para resolver la parte 1 de esta pregunta:

    location / {
            rewrite ^([^.]*[^/])$ $1/ permanent;
            try_files $uri $uri/ /index.php =404;
            include fastcgi_params;
            fastcgi_pass php5-fpm-sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
    }

Reescribir ^([^.]*[^/])$ $1/ permanente; reescribe las direcciones que no son de archivo (direcciones sin extensiones de archivo) para tener un "/" al final. Hice esto porque me estaba topando con " Acceso denegado."mensaje cuando traté de acceder a la carpeta sin ella.

Try_files $uri $uri/ /index.php = 404; se toma prestada de la respuesta de SanjuD, pero con un redireccionamiento 404 adicional si la ubicación aún no lo es encontrar.

Índice Fastcgi_index.php; fue la última pieza del rompecabezas que me faltaba. La carpeta no se redirigió al índice.php sin esta línea.

 1
Author: Brett Pennings,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-12 21:12:56

Si desea pasar solo el índice.php (no se pasará ningún otro archivo php a fastcgi) a fastcgi en caso de que tenga rutas como esta en un framework como codeigniter

$route["/download.php"] = "controller/method";


location ~ index\.php$ {
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi.conf;
}
 0
Author: Sajjad Ashraf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-12 19:18:00

Aquí está la respuesta de su 2da pregunta:

   location / {
        rewrite ^/(.*)$ /$1.php last;
}

Es trabajo para mí (basado en mi experiencia), significa que todos sus blabla.php reescribirá en blabla

Como http://yourwebsite.com/index.php a http://yourwebsite.com/index

 0
Author: Ariq Naufal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-20 14:16:57