在 NGiNX 中重写文件扩展名

在 NGiNX 中重写文件扩展名

我希望显示类似 domain.com/login 的文件,而不是 domain.com/login.php

我的 NGiNX 网站配置是:

#02API

server {
  # listen 80 deferred; # for Linux
  # listen 80 accept_filter=httpready; # for FreeBSD
  listen 80;

  # The host name to respond to
  server_name api.api.com;

  # Path for static files
  root /app/api/api;

  # Try static files first, then php
  index index.html index.htm index.php;

  # Specific logs for this vhost
  access_log /app/api/log/log-api-access.log;
  error_log  /app/api/log/log-api-error.log error;

  #Specify a charset
  charset utf-8;

  # Redirect needed to "hide" index.php
  location / {
    try_files $uri $uri/ /index.php?q=$uri&$args;
  }

  # Don't log robots.txt or favicon.ico files
  location ~* ^/(favicon.ico|robots.txt)$ {
    access_log off;
    log_not_found off;
  }
  # Custom 404 page
  error_page 404 /404.html;

  location ~* ^.+.(gif|jpg|jpeg|png|wmv|avi|mpg|mpeg|mp4|htm|html|js|css|mp3|swf|ico|flv|xml) {
    access_log off;
    expires 30d;
  }

  # 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;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }

  # Deny access to .htaccess
  location ~ /\.ht {
    deny all;
  }

  # Include the basic h5bp config set
  include h5bp/basic.conf;
}

但每次我尝试:domain.com/login

文件已下载,但domain.com/login.php 明显显示php文件内容。

有没有什么方法可以解决这个问题?

谢谢

答案1

如果您想使用 try_files 参数将 .php 添加到请求的 URL 末尾,请尝试用以下代码替换 try_files 行:

try_files $uri $uri/ $uri.php?$args;

或者,您可以为每个想要重写的 URL 添加重写,但这可能会变得混乱,具体取决于您想要对多少个文件执行此操作。

相关内容