Как я могу удалить index.php с адреса при перенаправлении запросов на index.php через fastcgi? - PullRequest
2 голосов
/ 16 октября 2010

У меня есть базовая настройка Magento (приложение PHP, использующее index.php в качестве контроллера) на сервере Ubuntu. Я настроил NGINX для использования PHP-CGI для обслуживания всех страниц PHP. Пока сайт работает должным образом, все URL имеют вид:
http://domain.com/index.php/apparel/shoes.html

Есть ли способ использовать параметр nginx rewrite , чтобы вместо этого я мог получить URL-адреса, подобные этому:
http://domain.com/apparel/shoes.html

В настоящее время это то, что у меня есть в файле конфигурации для обработки запросов страниц:

# catch rewritten and standard URLs
location ~* ^(/index.php)?(.*) {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root/index.php$1;
    fastcgi_read_timeout 600;
}

Спасибо.

Ответы [ 3 ]

3 голосов
/ 16 октября 2010

У меня есть некоторый опыт работы с nginx в этом отношении, и я даже написал об этом. Так что в бесстыдном акте саморекламы вот результат моего более раннего исследования:
http://www.magentocommerce.com/boards/viewreply/211050/


Прошло шесть лет, и вышеуказанная ссылка не работает. Также мои конфиги nginx более зрелые. Следующее начинается с блокировки всех файлов и разрешения только тех, которые явно являются публичными. Все остальные запросы переписываются на index.php. Если вы хотите выполнить какой-то другой файл PHP, вы должны написать собственное исключение. Это самый безопасный способ, о котором я могу думать.

/ и т.д. / Nginx / magento_server:

##
# Include from "server {}" block
##

# 1M = one month
expires 1M;
# recommended for all content, regardless
add_header X-Content-Type-Options "nosniff";

##
# Front handler
##

location / {
    # if is evil, except when it isn't
    if (-f $request_filename) {
        return 403;
    }
    rewrite ^ /index.php last;
}
location = /index.php {
    expires off;
    add_header X-Content-Type-Options    "nosniff";
    add_header X-Xss-Protection          "1; mode=block";

    # "php" must be defined as an upstream
    fastcgi_pass                         php;
    include                              fastcgi_params;
    fastcgi_param SCRIPT_FILENAME        $document_root/index.php;

    uninitialized_variable_warn          off;
    fastcgi_param MAGE_RUN_CODE          $mage_run_code if_not_empty;
    fastcgi_param MAGE_RUN_TYPE          $mage_run_type if_not_empty;
    fastcgi_param MAGE_IS_DEVELOPER_MODE $mage_is_developer_mode if_not_empty;
    fastcgi_param APPLICATION_ENV        $application_env if_not_empty;
    # same as max_execution_time in .htaccess
    fastcgi_read_timeout                 18000s;
}

##
# Whitelist public static files
#
# avoid regex where possible
##

location ^~ /media/ {
    # sometimes files are retrieved from database with get.php
    try_files $uri @mediaget;
}
# there is no way to call get.php directly
location @mediaget {
    add_header X-Content-Type-Options    "nosniff";
    add_header X-Xss-Protection          "1; mode=block";
    fastcgi_pass                         php;
    include                              fastcgi_params;
    fastcgi_param SCRIPT_FILENAME        $document_root/get.php;
}

location ^~ /skin/ {
    # allowed with defaults
}
location ^~ /js/ {
    # allowed with defaults
}

# should not be accessed normally since real favicon is in /skin/frontend
# however this is conventional
location = /favicon.ico {
    # pretty sure that it exists but just in case...
    log_not_found off;
}

# specific exclusions, still no regex
location = /media/.htaccess              { return 404; }
location ^~ /media/customer/             { return 404; }
location ^~ /media/downloadable/         { return 404; }

##
# Error handling
##

# possibly change this to Magento's no-route path
error_page 404 /errors/404.php;
location = /errors/404.php {
    fastcgi_pass                         php;
    include                              fastcgi_params;
    fastcgi_param SCRIPT_FILENAME        $document_root/errors/404.php;
}

# used when site is in maintenance mode
error_page 500 503 /errors/503.php;
location = /errors/503.php {
    fastcgi_pass                         php;
    include                              fastcgi_params;
    fastcgi_param SCRIPT_FILENAME        $document_root/errors/503.php;
}

# empty blocks allow serving without modification
# ideals for gzip and mime-type are already loaded
location ^~ /errors/default/css/         { }
location ^~ /errors/default/images/      { }
location ^~ /errors/enterprise/css/      { }
location ^~ /errors/enterprise/images/   { }

/ и т.д. / Nginx / conf.d / php.conf:

upstream php {
    server 127.0.0.1:9000;
    # add more PHP-FPM processes here if you have them, or maybe a unix socket
}

Каждый магазин имеет свой собственный серверный блок, подобный следующему:

/ и т.д. / Nginx / сайты с поддержкой / yoursite.com:

server {
    server_name        yoursite.com;
    root               /var/www;
    include            magento_server;
    set $mage_run_code "default";
    set $mage_run_type "website";
}

И так как .htaccess файлы игнорируются (потому что это не Apache), это помогает поместить .user.ini в каждый веб-корень:

/ вар / WWW / .user.ini

max_execution_time=600
memory_limit=256M
session.auto_start=off
session.gc_maxlifetime=31536000
0 голосов
/ 16 февраля 2012

Я не вижу нигде в ответах выше, где "/index.php/foo/bar" постоянно перенаправлялся на "/ foo / bar".После небольшого перебора, чтобы устранить проблему бесконечного перенаправления, я остановился на следующей начальной конфигурации, чтобы добиться этого:

server {
  listen 80;
  root /path/to/doc/root/;
  server_name foobar.com;

  # Perform 301 canonical redirect to remove index.php
  location ^~ /index.php {
    rewrite ^/index.php(.*)$ $scheme://$server_name$1 permanent;
  }

  #catch-all location block for all other URLs
  location / {
    #note: do not add "$uri/" before @handler, if you have an "index index.php" directive, it will auto redirect to "index.php" and cause an infinite loop due to the location block above
    try_files $uri @handler;
  }

  #internally add index.php back to the request
  location @handler {
    rewrite ^ /index.php$uri break;
    include php.conf;
  }

  #this will also allow other php files to be handled correctly
  #be careful here, see http://wiki.nginx.org/Pitfalls#Passing_Uncontrolled_Requests_to_PHP
  location ~ \.php {
    include php.conf;
  }
}

где php.conf содержит стандартную настройку параметров FastCGI, например:1004 *

fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param  PATH_INFO          $fastcgi_path_info;
fastcgi_param  PATH_TRANSLATED    $document_root$fastcgi_path_info;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

fastcgi_pass   127.0.0.1:9001;
fastcgi_index  index.php;
0 голосов
/ 16 октября 2010

Вы можете попробовать добавить правило переписывания, подобное этому

rewrite ^/(.*)/?$ /index.php/$1 break;

Извините, это не проверено, но должно быть близко. Больше информации: http://wiki.nginx.org/NginxHttpRewriteModule

...