Установка пререквизитов и компиляция минимального nginx для reverse-proxy
apt-get install build-essential libwww-perl libpcre3-dev zlib1g-dev libssl-dev wget http://nginx.org/download/nginx-1.0.14.tar.gz tar -xvf nginx-1.0.14.tar.gz cd nginx-1.0.14 make clean; ./configure --without-http_autoindex_module --without-http_browser_module --without-http_fastcgi_module --without-http_geo_module --without-http_empty_gif_module --without-http_map_module --without-http_memcached_module --without-http_ssi_module --without-http_userid_module --without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module --without-http_split_clients_module --without-http_uwsgi_module --without-http_scgi_module --without-http_referer_module --without-http-cache --without-http_upstream_ip_hash_module --with-http_ssl_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log make make install
Запуск nginx
/usr/local/nginx/sbin/nginx
Перезапуск nginx
kill $(cat /usr/local/nginx/logs/nginx.pid) && /usr/local/nginx/sbin/nginx
После первого запуска:
chown www-data /usr/local/nginx/proxy_temp -R chmod 777 /usr/local/nginx/proxy_temp
/usr/local/nginx/conf/nginx.conf
user www-data;
worker_processes 20;
worker_rlimit_nofile 32768;
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 10240;
}
http {
#log_format upstream '$upstream_addr | $request - [ $upstream_response_time ]';
server_tokens off;
client_header_timeout 3m;
send_timeout 3m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
output_buffers 1 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
client_max_body_size 20M;
tcp_nodelay on;
keepalive_timeout 75 20;
server_names_hash_bucket_size 128; # this seems to be required for some vh
log_format main '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
# default virtual host
server {
listen 80 default;
server_name _;
#access_log /var/log/nginx/upstream_access.log upstream;
access_log /var/log/nginx/default-access.log main;
server_name_in_redirect off;
location / {
index index.html;
root /var/www/default/htdocs;
}
}
# here resides my virtual host configurations
include /usr/local/nginx/conf/virtual.conf;
}
/usr/local/nginx/conf/virtual.conf
server {
listen 80;
listen 443;
include /usr/local/nginx/conf/ssl.conf;
server_name autosys.tk;
location / {
proxy_pass http://autosys.tk;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
/usr/local/nginx/conf/ssl.conf
ssl on; ssl_protocols SSLv3 TLSv1; ssl_certificate /usr/local/nginx/conf/ssl/cert.pem; ssl_certificate_key /usr/local/nginx/conf/ssl/cert.key;
mkdir /usr/local/nginx/conf/ssl
Для большей безопасности ограничиваем доступ к сертификатам:
chown www-data:www-data /usr/local/nginx/conf/ssl chmod 700 /usr/local/nginx/conf/ssl
Перейдем в эту папку и с генерируем сертификат:
cd /usr/local/nginx/conf/ssl openssl req -new -x509 -days 9999 -nodes -out cert.pem -keyout cert.key
Если через nginx не проходят куки!
apt-get install libpcre3 libpcre3-dev libperl-dev lua5.1 liblua5.1-dev
Устанавливаем LuaJIT-2.0
wget http://luajit.org/download/LuaJIT-2.0.0-beta10.tar.gz tar -xvf LuaJIT-2.0.0-beta10.tar.gz cd LuaJIT-2.0.0-beta10 make && make install ln -s /usr/local/lib/liblua5.1.so /usr/local/lib/liblua.so export LUAJIT_LIB=/usr/local/lib/ export LUAJIT_INC=/usr/local/include/luajit-2.0/ LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH
Скачиваем и распаковываем ngx_devel_kit
wget https://github.com/simpl/ngx_devel_kit/tarball/master tar -xvf master.1
Скачиваем и распаковываем lua-nginx-module
wget https://github.com/chaoslawful/lua-nginx-module/tarball/master tar -xvf master
Конфигурируем и компилируем и устанавливаем nginx
Надо следить за
--add-module=/root/chaoslawful-lua-nginx-module-d0d9140/ --add-module=/root/simpl-ngx_devel_kit-4192ba6/
в конце строки.
make clean; ./configure --without-http_autoindex_module --without-http_browser_module --without-http_fastcgi_module --without-http_geo_module --without-http_empty_gif_module --without-http_map_module --without-http_memcached_module --without-http_ssi_module --without-http_userid_module --without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module --without-http_split_clients_module --without-http_uwsgi_module --without-http_scgi_module --without-http_referer_module --without-http-cache --without-http_upstream_ip_hash_module --with-http_ssl_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=/root/chaoslawful-lua-nginx-module-d0d9140/ --add-module=/root/simpl-ngx_devel_kit-4192ba6/ make -j2 make install
После make install не забываем перезапустить nginx.
Перезапускаем
kill $(cat /usr/local/nginx/logs/nginx.pid) && /usr/local/nginx/sbin/ngin
И смотрим что же получилось? А получилась вот такая великолепная штука: http://wiki.nginx.org/HttpLuaModule, которая по уверению его создателей на среднем настольном ПК тянет 25 тысяч запросов в секунду. Внимательно изучив документацию становится понятно, что в среде исполнения Lua доступны все события и внутренние обработчики Nginx. Конкретно для нашей задачи мы будем использовать директиву header_filter_by_lua . Открываем конфигурационный файл, выбираем нужный location и добавляем простой код:
header_filter_by_lua '
local headers = ngx.header["Set-Cookie"]
if headers then
if type(headers) == "string" then
headers = {headers}
end
for i, header in ipairs(headers) do
local cookie = ngx.re.match(header, "JSESSIONID=([^;]+);", "io")
if cookie then
headers[i] = "JSESSIONID=" .. cookie[1] .. "; domain=.frontend.com; path=/newpath;"
end
end
ngx.header["Set-Cookie"] = headers
end
';
Тут приведен самый простой вариант обработчика — первый код на lua который я увидел в своей жизни. Можно и нужно написать универсальный парсер хедеров Set-Cookie, страна уже ждет своего героя в комментариях!
Discussion