[Nginx] Rewrite Rule

nginx rewrite

도메인이 www 로 시작하지 않는 것을 www로 가게

Query Parameter 삭제

      • nginx rewrite는 rewrite 후에 쿼리 파라미터를 자동으로 붙여버린다.
      • 쿼리 파라미터가 붙는 것을 막으려면 타겟 URL의 끝에 물음표(?)가 있어야 한다.
        rewrite ^ http://www.example.com/? last; # 쿼리 파라미터를 무시하고 무조건 http://www.example.com 으로 보내버림

http로 온 것을 모두 https

[기타] SPF 메일서버 등록 제도

메일서버등록제(SPF: Sender Policy Framework)

메일서버 정보를 사전에 DNS에 공개 등록함으로써 수신자로 하여금 이메일에 표시된 발송자 정보가 실제 메일서버의 정보와 일치하는지를 확인할 수 있도록 하는 인증기술

* 대다수 스팸발송자가 자신의 신원을 감추기 위하여 발송자 주소나 전송경로를 허위로 표기하거나 변경하는 경우가 많다는데 착안

SPF를 이용한 이메일 인증절차:

발신자 : 자신의 메일서버 정보와 정책을 나타내는 SPF 레코드를 해당 DNS에 등록

수신자 : 이메일 수신시 발송자의 DNS에 등록된 SPF 레코드를 확인하여 해당 이메일에 표시된 발송IP와 대조하고 그 결과값에 따라 수신여부를 결정

(메일서버나 스팸차단솔루션에 SPF 확인기능이 설치되어 있어야 함)

SPF 개발 및 도입현황:

1998년 Paul Vixie의 ‘Repudiating Mail From’에서 처음으로 아이디어가 제안된 이후 Pobox.com의 Meng Weng Wong에 의해 SPF가 개발됨

2004년 2월 IETF(Internet Engineering Task Force)에 공식 RFC(Request For Comments)로 제안되었으며, 2004년 12월 SPF의 모든 기술적 내용들이 최종 완성됨

SPF는 타 인증기술에 비해 적용이 용이하고 호환성이 좋으며 오픈소스를 기반으로 하므로 전 세계적으로 폭넓은 지지기반을 확보하고 있음

한국을 비롯한 미국, 캐나다, 일본 등 여러 국가들이 정부차원에서 사업자들을 대상으로 SPF 레코드 출판 및 확인기능 도입을 통한 스팸차단 활용을 적극 권고하고 있음

* SPF 란 무엇이며 설정의 필요성은

: 메일 헤더는 쉽게 위/변조 될 수 있으며, /변조된 발신지 정보로 스팸메일을 발송하는 경우가 많습니다.

만약 보낸이 주소가 hanbiro@hanbiro.com이다면 hanbiro.com의 메일서버에서 보내겠지요. 그래야 정상입니다.

그런데 다른서버를 이용해서 보냈을 경우 메일을 받는 서버에서 보낸메일서버의 아이피와 실제 hanbiro.com의 메일서버를 비교해서 같지 않을 경우 Fail을 표시하는 것입니다.

그러기 위해서 인가된 호스트 및 아이피를 도메인의 Zone 파일에서 SPF레코드를 설정합니다.

SPF기능 적용으로 지금 당장은 포탈의 이메일을 가장해서 보내는 스팸메일에 적용을 합니다.

SPF의 값이 Fail시 거의 99.9%의 스팸메일로 인식됩니다.

* SPF 판정값

: None -> 발신 도메인 SPF 레코드 적용하지 않았거나, 발신자 정보에서 해당 도메인의 정보를 확인 할 수 없음.

Netural -> 발신 도메인에 대한 위/변조 여부 판단 하지 않음.

Pass -> 메일 헤더가 위/변조 되지 않음.

Fail -> 메일 헤더가 위/변조 되었음.

Softfail -> 메일 헤더가 위/변조 되었으나, 메일 포워딩등의 서비스처럼 적법하게 위조 있음.

TempError -> 메일 수신 서버에서 SPF 확인시 문제 발생.

PermError -> 발송 도메인에 출판된 SPF 레코드값의 오류 발생. 

참고사이트

   SPF(Sender Policy Framework) 공식 홈페이지http://www.openspf.org/

   SPF위키피디아http://en.wikipedia.org/wiki/Sender_Policy_Framework

   QMail 에서 SPF 설정http://aramjo.blog.me/120102169083

[기타] 구글 크롤링 관련 ( robots.txt – 스크랩)

로봇 배제 표준

위키백과, 우리 모두의 백과사전.

“Robots.txt”는 이 문서를 가리킵니다. 위키백과의 Robots.txt의 파일을 보실려면, 미디어위키:Robots.txt 와 ko.wikipedia.org/robots.txt를 참조하시길 바랍니다.

로봇 배제 표준은 웹 사이트에 로봇이 접근하는 것을 방지하기 위한 규약으로, 일반적으로 접근 제한에 대한 설명을 robots.txt에 기술한다.

이 규약은 1994년 6월에 처음 만들어졌고, 아직 이 규약에 대한 RFC는 없다.

이 규약은 권고안이며, 로봇이 robots.txt 파일을 읽고 접근을 중지하는 것을 목적으로 한다. 따라서, 접근 방지 설정을 하였다고 해도, 다른 사람들이 그 파일에 접근할 수 있다.

목차

[숨기기]

[편집]

만약 모든 로봇에게 문서 접근을 허락하려면, robots.txt에 다음과 같이 입력하면 된다.

User-agent: *
Allow: /

모든 로봇을 차단하려면, robots.txt에 다음과 같이 입력하면 된다.

User-agent: *
Disallow: /

모든 로봇에 세 디렉터리 접근을 차단하려면, robots.txt에 다음과 같이 입력하면 된다.

User-agent: *
Disallow: /cgi-bin/
Disallow: /tmp/
Disallow: /junk/

모든 로봇에 특정 파일 접근을 차단하려면, robots.txt에 다음과 같이 입력하면 된다.

User-agent: *
Disallow: /directory/file.html

BadBot 로봇에 모든 파일 접근을 차단하려면, robots.txt에 다음과 같이 입력하면 된다.

User-agent: BadBot
Disallow: /

BadBot 과 Googlebot 로봇에 특정 디렉터리 접근을 차단하려면, robots.txt에 다음과 같이 입력하면 된다.

User-agent: BadBot
User-agent: Googlebot
Disallow: /private/

다양하게 조합하여 사용 할 수 있다.

User-agent: googlebot        # googlebot 로봇만 적용
Disallow: /private/          # 이 디렉토리를 접근 차단한다.

User-agent: googlebot-news   # googlebot-news 로봇만 적용
Disallow: /                  # 모든 디렉토리를 접근 차단한다.

User-agent: *                # 모든 로봇 적용
Disallow: /something/        # 이 디렉토리를 접근 차단한다.

대안[편집]

HTML의 meta 태그를 이용할 수도 있다.

<meta name=”Robots” content=”Noindex,Nofollow” />

하지만 이러한 방법은 일반적인 방법이 아니고, 아직까지는 일부의 로봇만이 지원한다.

각주[편집]

 

바깥 고리[편집]

[기타] 신뢰할수 있는 루트 인증서 등록 하는 법

Mac OS X

Add

Use command:

sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/new-root-certificate.crt

Remove

Use command:

sudo security delete-certificate -c “<name of existing certificate>”

Windows

Add

Use command:

certutil -addstore -f “ROOT” new-root-certificate.crt

Remove

Use command:

certutil -delstore “ROOT” serial-number-hex

Linux (Ubuntu, Debian)

Add

  1. Copy your CA to dir /usr/local/share/ca-certificates/
  2. Use command:

sudo cp foo.crt /usr/local/share/ca-certificates/foo.crt

  1. Update the CA store:

sudo update-ca-certificates

Remove

  1. Remove your CA.
  2. Update the CA store:

sudo update-ca-certificates –fresh

Restart Kerio Connect to reload the certificates in the 32-bit versions or Debian 7.

Linux (CentOs 6)

Add

  1. Install the ca-certificates package:

yum install ca-certificates

  1. Enable the dynamic CA configuration feature:

update-ca-trust force-enable

  1. Add it as a new file to /etc/pki/ca-trust/source/anchors/:

cp foo.crt /etc/pki/ca-trust/source/anchors/

  1. Use command:

update-ca-trust extract

Restart Kerio Connect to reload the certificates in the 32-bit version.

Linux (CentOs 5)

Add

Append your trusted certificate to file /etc/pki/tls/certs/ca-bundle.crt

cat foo.crt >> /etc/pki/tls/certs/ca-bundle.crt

Restart Kerio Connect to reload the certificates in the 32-bit version.

[linux] BASE64 Encode / Decode 손쉽게 이용하기

 

Php를 이용해서 아래와 같이 편하게 할 수 있음

#!/bin/bash -e

INPUT=$1;

 

if [ -z $INPUT ];

then

echo ” Input your encoding Plain text”

else

php -r “echo base64_encode($INPUT);”;

echo “\n”;

fi

 

 

예전엔, 이렇게 openssl을 이용했엇따.

 

[root@jinstalk ~]# printf “mail.shhong” | openssl base64

bWFpbC5zaGhvbmc=

 

Decode는 해당 openssl을 이용해서 이런식으로 가능합니다.

#!/bin/bash -e

INPUT=$1;

 

if [ -z $INPUT ];

then

echo ” Input your decoding Base64Encoded text”

else

echo $INPUT | openssl base64 -d;

echo “”;

fi

 

[linux] RPM BUILD 환경 구성하기

#RPM BUILD INSTALL

yum install rpm-build

yum install redhat-rpm-config

#STATUS FOR RPM-BUILD

rpm -qs rpm-build

#Environment for BUILD

mkdir -p ~/rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS}

# rpm 설치시 /etc/rpm/macro.dist 설정

#아래 매크로는 따로 설정하지 않아도 동작함.

echo ‘%_topdir %(echo $HOME)/rpmbuild’ > ~/.rpmmacros

#COMPILER Install

yum install make gcc

# 쌘트 6에서 공식 지원하는건 gcc 4.4

# RH 프로젝트를 통해서 비공식적으로 파이선 2.7 버전과, gcc 4.8을 Virtual ENV 형태로 제공 받을 수 있음.

[nginx] best performance tuning _config & kernel param

nginx.conf

# This number should be, at maximum, the number of CPU cores on your system.
# (since nginx doesn’t benefit from more than one worker per CPU.)
worker_processes 24;

# Number of file descriptors used for Nginx. This is set in the OS with ‘ulimit -n 200000’
# or using /etc/security/limits.conf
worker_rlimit_nofile 200000;

# only log critical errors
error_log /var/log/nginx/error.log crit

# Determines how many clients will be served by each worker process.
# (Max clients = worker_connections * worker_processes)
# “Max clients” is also limited by the number of socket connections available on the system (~64k)
worker_connections 4000;

# essential for linux, optmized to serve many clients with each thread
use epoll;

# Accept as many connections as possible, after nginx gets notification about a new connection.
# May flood worker_connections, if that option is set too low.
multi_accept on;

# Caches information about open FDs, freqently accessed files.
# Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec.
# I recommend using some varient of these options, though not the specific values listed below.
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

# Buffer log writes to speed up IO, or disable them altogether
#access_log /var/log/nginx/access.log main buffer=16k;
access_log off;

# Sendfile copies data between one FD and other from within the kernel.
# More efficient than read() + write(), since the requires transferring data to and from the user space.
sendfile on;

# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers before calling sendfile,
# or for throughput optimization.
tcp_nopush on;

# don’t buffer data-sends (disable Nagle algorithm). Good for sending frequent small bursts of data in real time.
tcp_nodelay on;

# Timeout for keep-alive connections. Server will close connections after this time.
keepalive_timeout 30;

# Number of requests a client can make over the keep-alive connection. This is set high for testing.
keepalive_requests 100000;

# allow the server to close the connection after a client stops responding. Frees up socket-associated memory.
reset_timedout_connection on;

# send the client a “request timed out” if the body is not loaded by this time. Default 60.
client_body_timeout 10;

# If the client stops reading data, free up the stale client connection after this much time. Default 60.
send_timeout 2;

# Compression. Reduces the amount of data that needs to be transferred over the network
gzip on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable “MSIE [1-6]\.”;

sysctl.conf

# Increase system IP port limits to allow for more connections

net.ipv4.ip_local_port_range = 2000 65000

net.ipv4.tcp_window_scaling = 1

# number of packets to keep in backlog before the kernel starts dropping them
net.ipv4.tcp_max_syn_backlog = 3240000

# increase socket listen backlog
net.core.somaxconn = 3240000
net.ipv4.tcp_max_tw_buckets = 1440000

# Increase TCP buffer sizes
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = cubic

[nginx] HTTPS Optimizing (OCSP Stapling)

Nginx에서 HTTPS Optimizing

  1. 연결 인증서 캐싱(Connection credentials caching)

SSL/TLS의 대부분 오버헤드는 초기의 연결 setup이다.

 

이 연결을 캐싱하면 다음 요청들이 좀 더 빨라진다.

 

설정에 다음을 추가한다.

 

ssl_session_cache shared:SSL:20m;
ssl_session_timeout 10m;

이는 모든 워커 프로세스들 사이에 공유되는 캐쉬를 생성한다.

캐쉬 사이즈는 bytes이고 4000 세션은 1MB에 저장된다고 한다. 20MB는 80000 세션을 저장하게 될 것이다.

 

  1. SSL을 사용하지 않기~

 

SSL은 TLS에 의해 대체된다. SSL을 계속 이야기 하는 건 오래된 습관과 관습이 아닐까 한다.(이 건 원본 저자의 의견)

 

SSL은 몇 가지 약점을 가지고 있기 때문에(이건 찾아봐야 함) 실지적으로 다양한 공격이 있었다.

 

TLS를 지원 안 하는 브라우저는 IE 6이다. (굿바이 했으니~ 패스)

 

TLS의 최신 버전은 1.2다. 그러나 새로운 브라우저들과 라이브러리들이 여전히 TLS 1.0을 사용한다.

 

따라서 설정에 다음을 추가한다.

 

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

  1. 암호화 모듈들을 옵티마이징

 

저자가 왜 이것을 옵티마이징 해야하는지.. 사용할 때 안전한 것만 지정해서 쓰면 될 거 같은데.. 여튼 한 번 해봤다.

 

설정에 다음을 추가하고

 

ssl_prefer_server_ciphers on;

아래 설정 중에 하나면 선택해서 쓰면 된다. (옵션 1과 옵션 2의 차이는 원본 참조)

 

# Cipher suite option 1:
ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:!ADH:!AECDH:!MD5;

# Cipher suite option 2:
#ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;

# If you absolutely need IE8 compatibility, use this:
#ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:RSA+3DES:!ADH:!AECDH:!MD5;

  1. OCSP stapling

Online Certificate Status Protocol(OCSP) 는 현재 인증서의 폐지 상태를 체크하는 프로토콜이다. 브라우저가 인증서를 볼 때 해당 인증서가 폐지 안 됐는지 체크하기 위해 인증서를 발행한 곳과 접촉한다. 물론 이 것은 연결을 초기화하는데 오버헤드가 된다. 또한 이 과정에서 3자(인증서를 발행한 곳)가 포함되어서 프라이버시 이슈가 있다.

 

이것을 적용하려면 Nginx 1.3.7 이상이 필요하다.

그리고 인증서를 발행하는 사이트에 가서 아래 파일을 다운 받는다.

AddTrustExternalCARoot.crt PositiveSSLCA2.crt

우리는 Comodo 인증서를 다운 받기 때문에 아래 URL에서 다운받았다.

https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/853/74/addtrustexternalcaroot

https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/943/74/intermediate-positivessl-ca-2

 

그런 다음 한개의 파일로 합친다.

 

cat AddTrustExternalCARoot.crt PositiveSSLCA2.crt > trustchain.crt

이제 적절한 위치(예: /etc/nginx/cert/trustchain.crt)에 넣고 Nginx의 설정을 아래와 같이 추가한다.

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/cert/trustchain.crt;
resolver 8.8.8.8 8.8.4.4;

stapling과 관련 없이 resolver가 들어가 있다. 이건 DNS 주소이고 2개의 DNS주소는 구글의 public DNS 주소이다. 다른 DNS 주소를 넣어도 상관없다.

 

  1. Strict Transport Security

SPDY를 사용할 때 모든 HTTP 요청을 HTTPS로 redirect하고 싶다면 Strict Transport Security를 사용하고 싶을 거라고 하는데 SPDY를 사용 안 하므로 패스 했다.

 

  1. 적용 결과

적용해보니 https로 사용하는 우리 사이트에서는 약 400ms 정도 빨라졌다.

 

좀 더 정확한 내용을 보고 싶으면 아래 원본을 읽어 보시길~

 

 

원본:

https://bjornjohansen.no/optimizing-https-nginx

 

원본 위치 <http://chickenlabs.blogspot.kr/2014/08/nginx-https-optimizing.html>

[linux] Nginx proxy_pass 에서 origin URI 제공

톰켓 proxypass 시에 header 에 Original URI 전달하기.

관련해서 proxy backend   넘겨줄 X-Original-URI 말고 X-forwarded-URI 로도 넘겨주는 방법(동일?) 선택하면 될듯합니다.

참고 : http://nerds.qminderapp.com/request-url-behind-proxy.html

nginx 설정

header X-Original-URI

location / {

            proxy_set_header X-Original-URI $request_uri;

            proxy_pass http://127.0.0.1:8080/;

        }

         location /testuri {

            proxy_set_header X-Original-URI $request_uri;

            proxy_pass http://127.0.0.1:8080/;

        }

java 설정

request.getHeader(“X-Original-URI”); 

실제 패킷 분석 결과

(톰켓으로 넘어가는 loopback 8080 캡쳐 : # tcpdump i lo qexX port 8080)

get http://test.hongstalk.com

09:54:56.618161 00:00:00:00:00:00 (oui Ethernet) > 00:00:00:00:00:00 (oui Ethernet), IPv4, length 623: localhost.47502 > localhost.webcache: tcp 557

        0x0000:  4500 0261 210a 4000 4006 198b 7f00 0001  E..a!.@.@…….

        0x0010:  7f00 0001 b98e 1f90 7f44 b41a 86a9 4ace  ………D….J.

        0x0020:  8018 0200 0056 0000 0101 080a 4fc9 9511  …..V……O…

        0x0030:  4fc9 9511 4745 5420 2f20 4854 5450 2f31  O…GET./.HTTP/1

        0x0040:  2e30 0d0a 582d 4f72 6967 696e 616c 2d55  .0..X-Original-U

        0x0050:  5249 3a20 2f0d 0a48 6f73 743a 2031 3237  RI:./..Host:.127

get http://test.hongstalk.com/testuri

09:58:54.909510 00:00:00:00:00:00 (oui Ethernet) > 00:00:00:00:00:00 (oui Ethernet), IPv4, length 543: localhost.47504 > localhost.webcache: tcp 477

        0x0000:  4500 0211 f02b 4000 4006 4ab9 7f00 0001  E….+@.@.J…..

        0x0010:  7f00 0001 b990 1f90 59d0 c7ce 9d52 e649  ……..Y….R.I

        0x0020:  8018 0200 0006 0000 0101 080a 4fcd 37e4  …………O.7.

        0x0030:  4fcd 37e4 4745 5420 2f20 4854 5450 2f31  O.7.GET./.HTTP/1

        0x0040:  2e30 0d0a 582d 4f72 6967 696e 616c 2d55  .0..X-Original-U

        0x0050:  5249 3a20 2f74 6573 7475 7269 0d0a 486f  RI:./testuri..Ho

[기타] 레디스 커멘드라인 사용 꿀팁

Redis-cli

 

SCAN 0 COUNT 100 MATCH *

# 100개 제한 읽어오기. Keys * 보다 효율적임..

 

DEBUG OBJECT 키

# 해당 정보의 사이즈 lru , expire 정보등을 읽어옴

 

SETEX 키 시간 키밸류

# expire time을 걸어 아이템을 set 한다.

# setex hong 60 sungho 라고 입력하면, 60초간 hong이라는 키가 저장된다.

 

 

SLOWLOG GET

# get 으로 시작하는 카운트 중 시간이 오개걸리는 값을 반환한다..

# 일반적으로 겟 명령어에서 슬로우 로그가 발생하는 경우 해당 키값의 데이터가 용량이 가장 큰 (메모리를 많이 잡아먹는) 키 값이다..

# 레디스 운영 시 OOM redis Out Of Memory 같은 경우, 해당 키 또는 리스트의 값이 너무 큰 (보통 팝 과정 없이  잘못 쌓이는 push LIST에서 발생한다. )

# GET , RESET, LEN  등을 확인 할 수 있다.

 

Lpush, Lpop, Rpush , Rpop

# push 는 데이터를 입력하며, Left, Right로 데이터를 입력한다.

# pop 은 데이터를 읽는 개념이 아닌, 가져간다는 표현으로 pop을 통해 꺼내어진 데이터는 해당 데이터테이블에서 삭제된다.

# Lrange 명령을 통해서 대상이 지정된 범위의 리스트를 읽어온다. 0 은 시작점을 의미하고, -1 은 리스트의 끝 (오른쪽 마지막) 을 의미하므로, 모든 리스트에 저장된 데이터를 확인 할 때 사용한다.

# 모든 리스트에서 데이터를 꺼내어 쓰면, 데이터가 없다는 의미의 nil 을 표시한다.

# 예시 )

Rpush hong A B C

 

LRANGE hong 0 -1

“A”

“B”

“C”

 

Rpop hong

“C”

 

Rpop hong

“B”

 

Rpop hong

“A”

 

Rpop hong

(nil)

 

 

Redis-cli -h HOSTNAME –stat

# 레디스의 key count, memory Usage, clinet, blocked, requests, connections 정보를 알려줌..

 

Redis-cli -h HOSTNAME -c ‘keys hong*” | xargs redis-cli -h HOSTNAME DEL

# hong으로 시작하는 모든 키를 검색하여, 한번에 지우는 방법..