Установка Nginx + PHP на прошивку Padavan

Я все это дело ставил на маршрутизатор Xiaomi Mi Router 3G с прошивкой Padavan. Все прекрасно работает. Подразумевается что у вас уже включен Entware в настройках маршрутизатора.

Итак поехали:

Устанавливаем пакеты:

opkg install nginx php7-fastcgi php7-mod-ctype php7-mod-curl php7-mod-dom php7-mod-exif php7-mod-fileinfo php7-mod-gd php7-mod-gettext php7-mod-hash php7-mod-iconv php7-mod-intl php7-mod-json php7-mod-mbstring php7-mod-session php7-mod-simplexml php7-mod-sockets php7-mod-xml php7-mod-xmlreader php7-mod-xmlwriter php7-mod-zip php7-pecl-mcrypt

Правим /opt/etc/nginx/nginx.conf примерно до следующего вида, либо удаляем старый и копируем в него следующее (не забудьте поменять домены на свои, а также пути), в данном примере используется перенаправление с http на https соответственно у Вас должны быть установлены сертификаты SSL (мануал по установке SSL от Letsencrypt.org):

user  nobody nogroup;
worker_processes  1;

#error_log  /opt/var/log/nginx/error.log;
#error_log  /opt/var/log/nginx/error.log  notice;
#error_log  /opt/var/log/nginx/error.log  info;

pid        /opt/var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    index index.php index.html index.htm;

    access_log off;

    sendfile        on;
    tcp_nopush      on;
    keepalive_timeout  65;
    gzip on;
    server_tokens     off;

server {
    listen 80 default_server;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name klimov.su www.klimov.su;
    root /opt/share/www/klimov.su;

    ssl_certificate /opt/etc/ssl/klimov.su.fullchain.pem;
    ssl_certificate_key /opt/etc/ssl/klimov.su.pem;
    ssl_dhparam /opt/etc/ssl/dhparam.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;
    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security max-age=15768000;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    resolver 1.1.1.1 1.0.0.1;

    location ~ /\. {
        deny all;
    }
    location ~ ~$ {
        deny all;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info   ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
        return 404;
        }
        root /opt/share/www/klimov.su;
        fastcgi_pass   unix:/opt/var/run/php-fcgi.sock;
        fastcgi_index  index.php;
        include        fastcgi_params;
    }   
}
server {
    listen 443 ssl;
    server_name blog.klimov.su;
    root /opt/share/www/blog.klimov.su;

    ssl_certificate /opt/etc/ssl/klimov.su.fullchain.pem;
    ssl_certificate_key /opt/etc/ssl/klimov.su.pem;
    ssl_dhparam /opt/etc/ssl/dhparam.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;
    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security max-age=15768000;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    resolver 1.1.1.1 1.0.0.1;

    location ~ /\. {
        deny all;
    }
    location ~ ~$ {
        deny all;
    }
    location ~ /config/ {
        deny all;
    }
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info   ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
        return 404;
        }
        root /opt/share/www/blog.klimov.su;
        fastcgi_pass   unix:/opt/var/run/php-fcgi.sock;
        fastcgi_index  index.php;
        include        fastcgi_params;
    }   
}
}

Также правим /opt/etc/nginx/fastcgi_params (добавим пару строк либо удаляем старый и создаём новый):

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_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  PATH_INFO          $fastcgi_path_info;
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  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

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;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

Создаем скрипт запуска php:

nano /opt/etc/init.d/S79php7-fcgi 

Добавляем в него:

#!/bin/sh

export PHP_FCGI_CHILDREN=''

ENABLED=yes
PROCS=php-fcgi
ARGS="-b /opt/var/run/php-fcgi.sock"
PREARGS=""
DESC=$PROCS
PATH=/opt/bin:/opt/sbin:/opt/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

. /opt/etc/init.d/rc.func

И делаем его исполняемым:

chmod +x /opt/etc/init.d/S79php7-fcgi

Правим php.ini:

nano /opt/etc/php.ini

Содержимое приводим к такому виду (при необходимости меняем нужные Вам параметры):

[PHP]
zend.ze1_compatibility_mode = Off

; Language Options

engine = On
;short_open_tag = Off
precision   =  12
y2k_compliance = On
output_buffering = Off
;output_handler =
zlib.output_compression = Off
;zlib.output_compression_level = -1
;zlib.output_handler =
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 100

;open_basedir =
disable_functions =
disable_classes =

; Colors for Syntax Highlighting mode.  Anything that's acceptable in
; <span style="color: ???????"> would work.
;highlight.string  = #DD0000
;highlight.comment = #FF9900
;highlight.keyword = #007700
;highlight.bg   = #FFFFFF
;highlight.default = #0000BB
;highlight.html = #000000

;ignore_user_abort = On
;realpath_cache_size = 16k
;realpath_cache_ttl = 120

; Miscellaneous

expose_php = Off

; Resource Limits

max_execution_time = 30    ; Maximum execution time of each script, in seconds.
max_input_time = 60    ; Maximum amount of time each script may spend parsing request data.
;max_input_nesting_level = 64
memory_limit = 12M    ; Maximum amount of memory a script may consume.

; Error handling and logging

; Error Level Constants:
; E_ALL             - All errors and warnings (includes E_STRICT as of PHP 6.0.0)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                   from a bug in your code, but it's possible that it was
;                   intentional (e.g., using an uninitialized variable and
;                   relying on the fact it's automatically initialized to an
;                   empty string)
; E_STRICT           - run-time notices, enable to have PHP suggest changes
;                   to your code which will ensure the best interoperability
;                   and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                   initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; E_DEPRECATED      - warn about code that will not work in future versions
;                   of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
;
; Common Values:
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices and coding standards warnings.)
;   E_ALL & ~E_NOTICE | E_STRICT  (Show all errors, except for notices)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
;   E_ALL | E_STRICT  (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
error_reporting  =  E_ALL & ~E_NOTICE & ~E_STRICT

display_errors = On
display_startup_errors = Off
log_errors = Off
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
;report_zend_debug = 0
track_errors = Off
;html_errors = Off
;docref_root = "/phpmanual/"
;docref_ext = .html
;error_prepend_string = "<font color=#ff0000>"
;error_append_string = "</font>"
; Log errors to specified file.
;error_log = /opt/var/log/php_errors.log
; Log errors to syslog.
;error_log = syslog

; Data Handling

;arg_separator.output = "&"
;arg_separator.input = ";&"
variables_order = "EGPCS"
request_order = "GP"
register_globals = Off
register_long_arrays = Off
register_argc_argv = On
auto_globals_jit = On
post_max_size = 8M
;magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
;default_charset = "iso-8859-1"
;always_populate_raw_post_data = On

; Paths and Directories

; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
doc_root =
user_dir =
extension_dir = "/opt/lib/php"
enable_dl = On
;cgi.force_redirect = 1
;cgi.nph = 1
;cgi.redirect_status_env = ;
cgi.fix_pathinfo=1
;fastcgi.impersonate = 1;
;fastcgi.logging = 0
;cgi.rfc2616_headers = 0

; File Uploads

file_uploads = On
upload_tmp_dir = "/opt/tmp"
upload_max_filesize = 8M
max_file_uploads = 20

; Fopen wrappers

allow_url_fopen = On
allow_url_include = Off
;from="[email protected]"
;user_agent="PHP"
default_socket_timeout = 60
;auto_detect_line_endings = Off

Проверяем корректность конфига nginx:

nginx -t

Если ошибок нет, то видим следующее:

nginx: the configuration file /opt/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /opt/etc/nginx/nginx.conf test is successful

Если есть ошибки, то сообщит с указанием строки.

Создаем каталоги (пути меняем на свои) для файлов сервера и файл, с выводом информации о РНР:

mkdir /opt/share/www/klimov.su
mkdir /opt/share/www/blog.klimov.su
echo "<?php phpinfo(); ?>" >> /opt/share/www/klimov.su/phpinfo.php

Стартуем сервисы:

/opt/etc/init.d/S79php7-fcgi start
/opt/etc/init.d/S80nginx start

Идем по адресу klimov.su/phpinfo.php (домен заменить на свой который указали в конфиге nginx, у домена должна быть "A" запись в DNS смотрящая на внешний IP адрес маршрутизатора, а также настроена переадресация портов об этом ниже) смотрим на вывод, если ничего нет — проверяем, что сделали не так.

Чтобы сервер был доступен извне идём в настройки WAN — Переадресация портов и включаем ручную переадресацию портов http с 80 внешнего на 80 локальный порт и для https c 443 внешнего на 443 локальный порт.

На этом всё, настройка сервера завершена. PHP скрипты ложем в /opt/share/www/klimov.su


Похожие статьи