RadarURL

소프트웨어
2013.04.08 08:42

Nginx 와 Apache 동시사용 설정 (영문)

조회 수 6362 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

가 크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

가 크게 작게 위로 아래로 댓글로 가기 인쇄

Reconfiguring Apache

There are two main aspects of your Apache configuration that will need to be edited in order to allow both Apache and Nginx to work together at the same time. But let us first clarify where we are coming from, and what we are going towards.

Configuration overview

At this point, you probably have the following architecture set up on your server:

  • A web server application running on port 80, such as Apache
  • A dynamic server-side script processing application such as PHP, communicating with your web server via CGI, FastCGI, or as a server module

The new configuration that we are going towards will resemble the following:

  • Nginx running on port 80
  • Apache or another web server running on a different port, accepting requests coming from local sockets only
  • The script processing application configuration will remain unchanged

As you can tell, only two main configuration changes will be applied to Apache as well as the other web server that you are running. Firstly, change the port number in order to avoid conflicts with Nginx, which will then be running as the frontend server. Secondly, (although this is optional) you may want to disallow requests coming from the outside and only allow requests forwarded by Nginx. Both configuration steps are detailed in the next sections.

Resetting the port number

Depending on how your web server was set up (manual build, automatic configuration from server panel managers such as cPanel, Plesk, and so on) you may find yourself with a lot of configuration files to edit. The main configuration file is often found in /etc/httpd/conf/ or /etc/apache2/, and there might be more depending on how your configuration is structured. Some server panel managers create extra configuration files for each virtual host.

There are three main elements you need to replace in your Apache configuration:

  • The Listen directive is set to listen on port 80 by default. You will have to replace that port by another such as 8080. This directive is usually found in the main configuration file.
  • You must make sure that the following configuration directive is present in the main configuration file: NameVirtualHost A.B.C.D:8080, where A.B.C.D is the IP address of the main network interface on which server communications go through.
  • The port you just selected needs to be reported in all your virtual host configuration sections, as described below.

The virtual host sections must be transformed from the following template

<VirtualHost A.B.C.D:80>
ServerName example.com
ServerAlias www.example.com
[...]
</VirtualHost>

to the following:

<VirtualHost A.B.C.D:8080>
ServerName example.com:8080
ServerAlias www.example.com
[...]
</VirtualHost>

In this example, A.B.C.D is the IP address of the virtual host and example.com is the virtual host's name. The port must be edited on the first two lines.

Accepting local requests only

There are many ways you can restrict Apache to accept only local requests, denying access to the outside world. But first, why would you want to do that? As an extra layer positioned between the client and Apache, Nginx provides a certain comfort in terms of security. Visitors no longer have direct access to Apache, which decreases the potential risk regarding all security issues the web server may have. Globally, it's not necessarily a bad idea to only allow access to your frontend server.

The first method consists of changing the listening network interface in the main configuration file. The Listen directive of Apache lets you specify a port, but also an IP address, although, by default, no IP address is selected resulting in communications coming from all interfaces. All you have to do is replace the Listen 8080 directive by Listen 127.0.0.1:8080; Apache should then only listen on the local IP address. If you do not host Apache on the same server, you will need to specify the IP address of the network interface that can communicate with the server hosting Nginx.

The second alternative is to establish per-virtual-host restrictions:

<VirtualHost A.B.C.D:8080>
ServerName example.com:8080
ServerAlias www.example.com
[...]
Order deny,allow
allow from 127.0.0.1
allow from 192.168.0.1
eny all
</VirtualHost>

Using the allow and deny Apache directives, you are able to restrict the allowed IP addresses accessing your virtual hosts. This allows for a finer configuration, which can be useful in case some of your websites cannot be fully served by Nginx.

Once all your changes are done, don't forget to reload the server to make sure the new configuration is applied, such as service httpd reload or /etc/init.d/ httpd reload.

Configuring Nginx

There are only a couple of simple steps to establish a working configuration of Nginx, although it can be tweaked more accurately as seen in the next section.

Enabling proxy options

The first step is to enable proxying of requests from your location blocks. Since the proxy_pass directive cannot be placed at the http or server level, you need to include it in every single place that you want to be forwarded. Usually, a location / { fallback block suffices since it encompasses all requests, except those that match location blocks containing a break statement.

Here is a simple example using a single static backend hosted on the same server:

server {
server_name .example.com;
root /home/example.com/www;
[...]
location / {
proxy_pass http://127.0.0.1:8080;
}
}

In the following example, we make use of an Upstream block allowing us to specify multiple servers:

upstream apache {
server 192.168.0.1:80;
server 192.168.0.2:80;
server 192.168.0.3:80 weight=2;
server 192.168.0.4:80 backup;
}
server {
server_name .example.com;
root /home/example.com/www;
[...]
location / {
proxy_pass http://apache;
}
}

So far, with such a configuration, all requests are proxied to the backend server; we are now going to separate the content into two categories:

  • Dynamic files: Files that require processing before being sent to the client, such as PHP, Perl, and Ruby scripts, will be served by Apache
  • Static files: All other content that does not require additional processing, such as images, CSS files, static HTML files, and media, will be served directly by Nginx

We thus have to separate the content somehow to be provided by either server.

Separating content

In order to establish this separation, we can simply use two different location blocks—one that will match the dynamic file extensions and another one encompassing all the other files. This example passes requests for .php files to the proxy:

server {
server_name .example.com;
root /home/example.com/www;
[...]
location ~* \.php.$ {
# Proxy all requests with an URI ending with .php*
# (includes PHP, PHP3, PHP4, PHP5...)
proxy_pass http://127.0.0.1:8080;
}
location / {
# Your other options here for static content
# for example cache control, alias...
expires 30d;
}
}

This method, although simple, will cause trouble with websites using URL rewriting. Most Web 2.0 websites now use links that hide file extensions such as http://example.com/articles/us-economy-strengthens/; some even replace file extensions with links resembling the following:http://example.com/useconomy- strengthens.html.

When building a reverse-proxy configuration, you have two options:

  • Port your Apache rewrite rules to Nginx (usually found in the .htaccess file at the root of the website), in order for Nginx to know the actual file extension of the request and proxy it to Apache correctly.
  • If you do not wish to port your Apache rewrite rules, the default behavior shown by Nginx is to return 404 errors for such requests. However, you can alter this behavior in multiple ways, for example, by handling 404 requests with the error_page directive or by testing the existence of files before serving them. Both solutions are detailed below.

Here is an implementation of this mechanism, using the error_page directive :

server {
server_name .example.com;
root /home/example.com/www;
[...]
location / {
# Your static files are served here
expires 30d;
[...]
# For 404 errors, submit the query to the @proxy
# named location block
error_page 404 @proxy;
}

location @proxy {
proxy_pass http://127.0.0.1:8080;
}
}

Alternatively, making use of the if directive from the Rewrite module:

server {
server_name .example.com;
root /home/example.com/www;
[...]
location / {
# If the requested file extension ends with .php,
# forward the query to Apache
if ($request_filename ~* \.php.$) {
break; # prevents further rewrites
proxy_pass http://127.0.0.1:8080;
}
# If the requested file does not exist,
# forward the query to Apache
if (!-f $request_filename) {
break; # prevents further rewrites
proxy_pass http://127.0.0.1:8080;
}
# Your static files are served here
expires 30d;
}
}

There is no real performance difference between both solutions, as they will transfer the same amount of requests to the backend server. You should work on porting your Apache rewrite rules to Nginx if you are looking to get optimal performance.

 

출처 : http://wyseburn.tistory.com/archive/20110817

?

공부 게시판

공부에 도움되는 글을 올려주세요.

  1. [공지] 공부 게시판 입니다.

    Date2003.08.18 By처누 Views2016907
    read more
  2. 유심&통장 [카,톡] sim256 (24시문의) 대포유심 대포통장판매 선불유심팝니다 대포유심팝니다

    Date2026.10.06 Category윈도우즈 By놀라운운석99 Views1
    Read More
  3. 대전누수, 근본 원인 해결의 시작

    Date2026.10.06 Category사무 소프트웨어 By적막한체이서42 Views1
    Read More
  4. 강남건전지❤️OlO-8655-OO53❤️친절문의환영 #강남건전지 #강남유니콘 #선릉유니콘 #강남건전지위치 #선릉역건전지#대치동유니콘 #강남바커스 #선릉바커스 #선릉역바커스 #강남룸클럽 #선릉룸클럽 #강남베터리 #강남바데리

    Date2026.10.05 Category데이터베이스 By괴랄한재규어89 Views1
    Read More
  5. 용인두피문신 고민? 만족 후기 보려면

    Date2026.10.05 Category사무 소프트웨어 By날카로운꿩11 Views12
    Read More
  6. 웨딩누브라, 완벽한 드레스 핏을 위한 선택

    Date2026.10.05 Category윈도우즈 By날카로운감시자22 Views5
    Read More
  7. 인천맛집 순위

    Date2026.10.05 Category가상화 By차가운파편97 Views2
    Read More
  8. 손목터널증후군 치료, 현명한 선택 기준은?

    Date2026.10.05 Category웹서버,WAS By괴상한두루미52 Views1
    Read More
  9. 최근 테헤란로 벤처 밸리의 핵심 리더들 사이에서 ‘클래스가 다른 정통 수질과 프라이빗 무드’로 소문 자자한 '선릉 룸싸롱' 기습 방문, 인공미를 거부하는 무결점 뉴페이스들과 심장을 마비시킨 사심 플러팅에 제대로 저격당하고 온 솔직 후기

    Date2026.10.05 Category가상화 By희미한홍학99 Views4
    Read More
  10. 카­톡 gusim8003 급전/내구제 (24시문의) 선불폰 소액결제 일수 급전대출

    Date2026.10.05 Category웹서버,WAS By황금빛섬광82 Views2
    Read More
  11. 흥신소 선택 가이드

    Date2026.10.05 Category데이터베이스 By흔들리는골렘32 Views2
    Read More
  12. 양산싱크대막힘 완벽 해결 뚫자하수구

    Date2026.10.05 Category윈도우즈 By몽환적인태양핵44 Views1
    Read More
  13. 양산싱크대막힘 신속 해결의 모든 것

    Date2026.10.05 Category가상화 By조용한치타58 Views4
    Read More
  14. 카카오*톡 gusim8003 내구제대출/상조내구제 [24시문의] 선불유심 대출 폰내구제 가개통

    Date2026.10.05 Category유닉스/리눅스 By하얀라마72 Views9
    Read More
  15. 종로구가라오케 010 2817 0845 종로구 가라오케 예약 및 문의

    Date2026.10.04 Category윈도우즈 By흐릿한분석가84 Views10
    Read More
  16. 성공적인 중고화물차 선택 가이드

    Date2026.10.04 Category가상화 By붉은불꽃77 Views7
    Read More
  17. 센텀르엘, 하이엔드 라이프의 새로운 기준

    Date2026.10.04 Category데이터베이스 By검은파편81 Views7
    Read More
  18. 양산싱크대막힘 완벽 해결 뚫자하수구

    Date2026.10.04 Category가상화 By매혹적인곰18 Views7
    Read More
  19. 동탄 미시보다 자극적 첫사랑보다 그리운 마블 노래클럽 010++8293++0291

    Date2026.10.03 Category사무 소프트웨어 By광휘의퀘이사47 Views7
    Read More
  20. 탄현동노래방 탄현동에서 찾는 노래방 010 2817 0845

    Date2026.10.03 Category웹서버,WAS By울리는고래상어65 Views16
    Read More
  21. [Rocky Linux 9] /home 용량 줄이고 /root 용량 늘리기

    Date2026.04.03 Category유닉스/리눅스 ByYooN Views3812
    Read More
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 36 Next
/ 36


즐겨찾기 (가족)

JAESOO's HOMEPAGE


장여은 홈페이지


장여희 홈페이지


장여원 홈페이지


즐겨찾기 (업무)

알리카페 홀릭

숭실대 컴퓨터 통신연구실 (서창진)

말레이시아 KL Sentral 한국인 GuestHouse


즐겨찾기 (취미)

어드민아이디

유에코 사랑회

아스가르드 좋은사람/나쁜사람

JServer.kr

제이서버 메타블로그

재수 티스토리


즐겨찾기 (강의, 커뮤니티)

재수 강의 홈페이지


한소리


VTMODE.COM


숭실대 인공지능학과


숭실대 통신연구실


베너