VPS Server Configuration Ubuntu + LAMP + Nginx method

Source: Internet
Author: User
Tags ack mysql in pack php file svn vps iptables least privilege

Web site Environment

LAMP. What is LAMP? It is Linux + Apache + MySQL + php/perl abbreviation, is a concise, strong, widely supported site environment. At home there seems to be a lot of people recommend to change A (Apache) to N (Nginx), but I do not recommend this, because Nginx relative to Apache, the support of PHP is worse, and lack of. htaccess directory-level configuration file support, rewrite function is not very Good. Most of all, LAMP is also an official recommended website environment for Ubuntu Server, so I choose lamp!

However, if you really have some preference for nginx, or you can add a nginx up, this time can be used as a reverse agent nginx, to some extent, to enhance the site's ability to resist pressure, especially some static files such as pictures.

Third, connect your Ubuntu VPS


Ubuntu Server uses a new version of the policy every six months, but every two years there is a "long-term support version", referred to as "lts",lts version of the Ubuntu server support period of up to five year, enough to use the server phase-out, scrap ... This tutorial is based on the Ubuntu Server 12.04 LTS Edition, which can be used until April 2017 ... You can also use a LTS version like 12.10.

After the VPS Control Panel has installed the operating system, the operation can be connected. Most operations on the Gnu/linux server are done by command, and OpenSSH is an excellent protocol for remote login gnu/linux. Windows users need to download software such as Tunnelier, user name, password to connect, OS X and Gnu/linux users can connect directly to the terminal using SSH command. For example, the VPS provider to your IP is 10.0.0.1, the user name is root, then the connection command is:

SSH root@10.0.0.1 and then press the prompt to enter the password. Gnu/linux password input is generally not back, that you do not see what you entered, but you did enter, enter the completion of the entry can begin to log in, the first time you log in will be prompted to save the public key, confirm.

The code is as follows Copy Code

wzyboy@vermilion:~$ SSH root@10.0.0.1
Welcome to Ubuntu 12.04 LTS (gnu/linux 3.2.0-24-virtual x86_64)

* documentation:https://help.ubuntu.com/
root@xehost:~#

At this point you are connected to your VPS, the next command will be in this window to complete the word. As mentioned earlier, the maintenance of the Gnu/linux server is basically done by command, so some commands are inevitably involved in this tutorial. Let's start with a simple, updated Ubuntu package:

The code is as follows Copy Code

root@xehost:~# apt-get update && apt-get upgrade
[...]
Do your want to continue [y/n]?

The operation will be performed for a while, finally ask you whether to continue, answer Y or directly press ENTER, the screen again ran a large number of characters, and so it stopped when the upgrade was completed, during the period if the Package manager asked you questions, generally keep the default selection can be. Note: This command does not upgrade the kernel, if you want to upgrade the kernel, please change the upgrade to Dist-upgrade, you may need to modify the corresponding GRUB settings to the next boot to the new kernel.

Earlier in the order, Apt-get is the Debian/ubuntu release of the upgrade manager, the use of the method is very simple and understandable, for example, we want to install Vim this very useful editor, the following command can be executed:

  code is as follows copy code
root@xehos t:~# apt-get Install VIM
Reading package lists ... Done
Building Dependency Tree
Reading State information ... Done
The following extra packages would be installed:
libpython2.7 vim-runtime
Suggested packages:
Ctags VI M-doc vim-scripts
The following new packages'll be installed:
libpython2.7 vim vim-runtime
0 upgraded, 3 new Ly installed, 0 to remove and 1 not upgraded.
Need to get 8,513 KB of archives.
After this operation, 28.0 MB of additional disk space would be used.
do your want to continue [y/n]? answer Y or direct return

, you can install the Vim editor. Vim Default color theme If it doesn't look good, use the echo ' ColorScheme evening ' > VIMRC command to convert it to the evening scheme, which is clearly seen on a black background.

If you want to remove a package, it is easy to use remove or purge, the latter will be removed with the configuration file, such as to remove Cryptsetup this package, is Apt-get purge cryptsetup.

Debian/ubuntu's Package Manager is dpkg, and there are some commands that start with dpkg. For example, to change the time zone, is dpkg-reconfigure tzdata, there will be a very pro-people selection interface appears, select Asia/shanghai can be changed to utc+8 time zone.

Ubuntu VPS Basic Operation explained, the following start to install the site environment.

Four, install LAMP + nginx


Install LAMP


What did I say? The Ubuntu server is a very useful release, and it's great to use on the server. In some backward also claiming "industry standard" distribution, installation LAMP to many complex commands, many parts also because too old to spend a lot of CPU and hard drive to compile, but under Ubuntu, as long as a simple command: www.111cn.net

Tasksel Install Lamp-server Next is fully automated operation, will prompt you to set a MySQL root password, others do not need manual intervention, the entire process within two minutes to complete. In this command, Tasksel is a suite of Ubuntu installation tools that make it easy to install some predefined suites. If some VPS hint without tasksel command, apt-get install Tasksel install a can. What if you still want to install a phpmyadmin? Apt-get Install phpMyAdmin can! The period will let you choose your site environment, press the space to select Apache2 then OK, will let you enter two password, one is the root password of MySQL, this is just you in install LAMP when set, I hope you have not forgotten ha. The other is set phpMyAdmin in MySQL in the program password, this can be directly enter, let it randomly generate a complex password, anyway this also do not human memory ...

Configure Apache

If you need to nginx as Apache reverse proxy, Apache needs to be configured, if you only want to use Apache directly, please skip this paragraph and the next paragraph.

It is important to note that Debian/ubuntu's Apache has been highly modified, with a significant difference from upstream, especially in the configuration file structure, adding a lot of handy commands and scripts. These handy things are not in other distributions.

Because you want to use Nginx as a reverse proxy for Apache, let Nginx listen to 80 ports and let Apache listen to a different one, such as port 8080. You need to make changes to/etc/apache2/ports.conf. Use Vim to open this file, locate to Listen 80 this line, change into Listen 127.0.0.1:8080, the other Namevirtualhost port also to be changed to 8080. 111cn.net

What, Vim how to use? There are two basic patterns in Vim, one is "normal", one is "edit", to enter the words need to press I, to return to the "normal" then press ESC, Vim novice words can be used to navigate to the corresponding position, and then press I into the "edit", make the appropriate changes and then press ESC back to " Normal ", then use: Wq carriage return command to save exit.

After the change, restart the Apache services: service apache2 restart. Restarting a service in Ubuntu is basically the same format.

Installing and configuring Nginx


How to install Nginx in Ubuntu Server? If you look at the contents of the above carefully, you can already guess:

Apt-get install Nginx An order, buttoned up. When configured, set up the corresponding configuration file in the/etc/nginx/sites-enabled/with Apache/etc/apache2/sites-enabled/and restart the nginx. Configuration file Example:

  code is as follows copy code

Server {
Listen 80;
server_name lamp.xehost.com;

Access_log/var/log/nginx/access.log;

Location/{
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;
Client_max_body_size 10m;
Client_body_buffer_size 128k;
Proxy_connect_timeout 90;
Proxy_send_timeout 90;
Proxy_read_timeout 90;
Proxy_buffers 4k;
Proxy_pass http://127.0.0.1:8080;
}

}

If you need a real IP module, you can install the LIBAPACHE2-MOD-RPAF package and change the/etc/apache2/mods-enabled/rpaf.conf to the following:

The code is as follows Copy Code

Rpafenable on
Rpafsethostname on
Rpafproxy_ips 127.0.0.1:: 1
Rpafheader x-forwarded-for

Now we're going to do some security configuration.

Basic Installation Configuration

1. Do not display the SVN version number

Vi/usr/local/nginx/conf/nginx.conf
Server_tokens off;

2. Filter. All files in SVN

Location ~ ^ (. *) \/\.svn\/
{
Deny all;
}

The code that is checked out directly from SVN contains. SVN and some of these files.

2. Filter phpinfo.php files

Location ~ ^ (. *) \/phpinfo.php
{
Deny all;
}

3. Nginx_status Restrict IP access

Location/nginx_status {
Stub_status on;
Access_log off;
Allow x.x.x.x;
Deny all;
}

5. Restricting access to the tools directory

Location ~ ^ (. *) \/tools\/
{
Allow x.x.x.x;
Deny all;
Fastcgi_pass 192.168.2.11:9000;
Fastcgi_index index.php;
Include fcgi.conf;
}

Php:

6. Expose_php=off

Block PHP from sending x-powered-by

php/5.3.6-13ubuntu3.3 Similar information

Nginx

7. Server_tokens off;

Block the detailed version number of the Send Nginx

8. Remove Fastcgi_param server_software nginx/$nginx _version; In the $nginx_version

Block version number of Nginx sent to CGI

9. Add in FastCGI

Set $fastcgi _sf $document _root$fastcgi_script_name;
if (!-e $fastcgi _sf) {
return 403;
}


nginx Default configuration file and default port

/usr/local/nginx/conf/–nginx Server configuration directory,/usr/local/nginx/conf/nginx.conf is the primary configuration file

/usr/local/nginx/html/– Default Document Location

/usr/local/nginx/logs/– Default log file location

Nginx http Default port: TCP 80

Nginx HTTPS default port: TCP 443

You can use the following command to test the correct configuration of Nginx:

#/usr/local/nginx/sbin/nginx–t

Output Example:

The configuration file/usr/local/nginx/conf/nginx.conf syntax is okconfiguration file/usr/local/nginx/conf/ Nginx.conf Test is successful

To have the modified configuration take effect, execute the following command:

#/usr/local/nginx/sbin/nginx-s Reload

If you want to stop the server, run:

#/usr/local/nginx/sbin/nginx-s Stop

1, open SELinux

SELinux (Secure enhanced Linux) is a Linux kernel feature that provides a mechanism to support access control security policies that provide great security protection against most system root-level attacks, and refer to "How to centos/red On the Hat system, open SELinux "(http://www.cyberciti.biz/faq/rhel-fedora-redhat-selinux-protection/).

Run the Getsebool–a command to view the SELinux settings:

getsebool-a | lessgetsebool-a | grep offgetsebool-a | grep o

Then use the Setsebool command to open the desired configuration item, noting that after opening the SELinux, the 2-8% overhead is usually increased on rhel or CentOS.

2, through the mount parameter to provide the least privilege

Create a separate partition for your/html/php file, for example, create a/DEV/SDA5 partition mount on/ngnix, and make sure that/ngnix uses Noexec,nodev and NOSETUID permission mounts. Here is one of my mount instances:

Label=/nginx/nginx ext3 Defaults,nosuid,noexec,nodev 1 2

Note that you need to create a new partition using the Fdisk and MKFS.EXT3 commands.

3, through/etc/sysctl.conf reinforcement

You can control and configure the Linux kernel and network settings through/etc/sysctl.conf.

In addition, please refer to:

# Avoid amplification attacks net.ipv4.icmp_echo_ignore_broadcasts = Open malicious ICMP error message Protection net.ipv4.icmp_ignore_bogus_error_responses = Activate SYN flood attack protection Net.ipv4.tcp_syncookies = open and record spoofing, source Routing and redirect pack Net.ipv4.conf.all.log_martians = 1net.ipv4.conf.default.log _martians = Net.ipv4.conf.all.accept_source_route = 0net.ipv4.conf.default.accept_source_route = The packet of the passive route = 0# Turn on reverse path filtering
Net.ipv4.conf.all.rp_filter = 1

Net.ipv4.conf.default.rp_filter = 1

# Make sure no one can modify the routing table

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.conf.default.accept_redirects = 0

net.ipv4.conf.all.secure_redirects = 0

net.ipv4.conf.default.secure_redirects = 0

# does not act as a router

Net.ipv4.ip_forward = 0

net.ipv4.conf.all.send_redirects = 0

net.ipv4.conf.default.send_redirects = 0

# Open Execshild

Kernel.exec-shield = 1

Kernel.randomize_va_space = 1

# IPV6 Settings

net.ipv6.conf.default.router_solicitations = 0

Net.ipv6.conf.default.accept_ra_rtr_pref = 0

Net.ipv6.conf.default.accept_ra_pinfo = 0

NET.IPV6.CONF.DEFAULT.ACCEPT_RA_DEFRTR = 0

net.ipv6.conf.default.autoconf = 0

Net.ipv6.conf.default.dad_transmits = 0

net.ipv6.conf.default.max_addresses = 1

# optimize the ports used by LB

# Increase System File Descriptor restrictions

Fs.file-max = 65535

# allow more PIDs (reduce rollover problems); May-Break Some programs 32768

Kernel.pid_max = 65536

# Increase system IP Port limits

Net.ipv4.ip_local_port_range = 2000 65000

# increase TCP Maximum buffer size

Net.ipv4.tcp_rmem = 4096 87380 8388608

Net.ipv4.tcp_wmem = 4096 87380 8388608

# Add Linux to automatically adjust TCP buffer limits

# Minimum, default and maximum number of bytes to use

# maximum value is not less than 4MB, if you use a very high BDP path can be set higher

# TCP Windows, etc.

Net.core.rmem_max = 8388608

Net.core.wmem_max = 8388608

Net.core.netdev_max_backlog = 5000

net.ipv4.tcp_window_scaling = 1

4. Remove all unwanted nginx modules

You need to minimize the Nginx load module, I mean to meet the needs of the Web server on it, redundant modules one does not stay, for example, the commands for disabling SSI and AutoIndex modules are as follows:

#./configure--without-http_autoindex_module--without-http_ssi_module# make# make install

When compiling the Nginx server, use the following command to see which modules should be enabled and which modules should be disabled:

#./configure--help | Less

Disable the Nginx module that you do not need.

Modify Nginx version header information (optional), edit src/http/ngx_http_header_filter_module.c:

# VI +48 src/http/ngx_http_header_filter_module.c

Locate the following two lines:

static char ngx_http_server_string[] = "Server:nginx" crlf;static char ngx_http_server_full_string[] = "Server:" Nginx_v ER CRLF;

Modify it to:

static char ngx_http_server_string[] = "Server:ninja Web server" Crlf;static char ngx_http_server_full_string[] = "Server : Ninja Web Server "CRLF;"

Save and close the file. You can now start compiling the server, adding the following configuration code to nginx.conf to prevent the Nginx version number from appearing on all automatically generated error pages:

Server_tokens off

5. Use Mod_security (for back-end Apache server only)

Mod_security provides Apache with an application-level firewall that installs Mod_security modules for all back-end Apache Web servers, which can prevent many injection attacks.

6, configure SELinux strategy to strengthen Nginx

By default, SELinux does not protect the Nginx Web server, can be manually configured for protection, and first installs the support package that SELinux needs at compile time:

# yum-y Install selinux-policy-targeted Selinux-policy-devel

Download the SELinux policy from the Project home page (http://sourceforge.net/projects/selinuxnginx/):

# cd/opt# wget ' HTTP://DOWNLOADS.SOURCEFORGE.NET/PROJECT/SELINUXNGINX/SE-NGIX_1_0_10.TAR.GZ?USE_MIRROR=NCHC '

Extract:

# TAR-ZXVF Se-ngix_1_0_10.tar.gz

Compile:

# CD se-ngix_1_0_10/nginx# make

Output Example:

Compiling targeted Nginx module/usr/bin/checkmodule:loading policy configuration from tmp/nginx.tmp/usr/bin/ Checkmodule:policy Configuration loaded/usr/bin/checkmodule:writing Binary representation (version 6) to Tmp/nginx.mod Creating targeted NGINX.PP policy Packagerm TMP/NGINX.MOD.FC

To install the generated nginx.pp SELinux module:

#/usr/sbin/semodule-i NGINX.PP

7, through the Iptables firewall set limits

The following firewall script can block all requests, allowing only:

Inbound HTTP request (TCP 80 port)

Inbound ICMP ping request

Outbound NTP request (Port 123)

Outbound SMTP request (TCP port 25)

#!/bin/bashipt= "/sbin/iptables" IPS ####### Get Server public ipserver_ip=$ (ifconfig eth0 | grep ' inet addr: ' | awk-f ' inet addr: ' {print $} ' | awk ' {print} '] lb1_ip= "204.54.1.1" lb2_ip= "204.54.1.2" to implement some intelligent logic so that we can use LB2 script Damm "" other_lb= "" [["$ Server_ip "= =" $LB 1_ip "]] && other_lb=" $LB 2_ip "| | other_lb= "$LB 1_ip" [["$OTHER _lb" = "$LB 2_ip"]] && opp_lb= "$LB 1_ip" | | opp_lb= "$LB 2_ip" ### IPs # # #PUB_SSH_ONLY = "122.xx.yy.zz/29" File #####
Blocked_ip_tdb=/root/.fw/blocked.ip.txt

spoofip= "127.0.0.0/8 192.168.0.0/16 172.16.0.0/12 10.0.0.0/8 169.254.0.0/16 0.0.0.0/8 240.0.0.0/4 255.255.255.255/32 168.254.0.0/16 224.0.0.0/4 240.0.0.0/5 248.0.0.0/5 192.0.2.0/24 "

badips=$ ([[F ${blocked_ip_tdb}]] && egrep-v "^#|^$" ${blocked_ip_tdb})

### Interface ###

Pub_if= "eth0" # public interface

Lo_if= "Lo" # loopback

Vpn_if= "eth1" # vpn/private Net

### Start Firewall ###

echo "Setting LB1 $ (hostname) Firewall ..."

# Delete and close everything

$IPT-P INPUT DROP

$IPT-P OUTPUT DROP

$IPT-P FORWARD DROP

# Unrestricted Lo Access

$IPT-A input-i ${lo_if}-j ACCEPT

$IPT-A output-o ${lo_if}-j ACCEPT

# Unrestricted access to Vpn/pnet

$IPT-A input-i ${vpn_if}-j ACCEPT

$IPT-A output-o ${vpn_if}-j ACCEPT

# Delete Sync

$IPT-A input-i ${pub_if}-P TCP! –syn-m state–state new-j DROP

# Delete Fragments

$IPT-A input-i ${pub_if}-f-j DROP

$IPT-A input-i ${pub_if}-P tcp–tcp-flags all fin,urg,psh-j DROP

$IPT-A input-i ${pub_if}-P tcp–tcp-flags all all-j DROP

# Delete Empty Packages

$IPT-A input-i ${pub_if}-P tcp–tcp-flags all none-m limit–limit 5/m–limit-burst 7-j log–log-prefix "NULL Packet S "

$IPT-A input-i ${pub_if}-P tcp–tcp-flags all none-j DROP

$IPT-A input-i ${pub_if}-P tcp–tcp-flags syn,rst syn,rst-j DROP

# Delete Xmas

$IPT-A input-i ${pub_if}-P tcp–tcp-flags syn,fin syn,fin-m limit–limit 5/m–limit-burst 7-j log–log-prefix "XMAS Packets "

$IPT-A input-i ${pub_if}-P tcp–tcp-flags syn,fin syn,fin-j DROP

# Delete Fin packet scans

$IPT-A input-i ${pub_if}-P tcp–tcp-flags fin,ack fin-m limit–limit 5/m–limit-burst 7-j log–log-prefix "FIN Pack ETS Scan "

$IPT-A input-i ${pub_if}-P tcp–tcp-flags fin,ack fin-j DROP

$IPT-A input-i ${pub_if}-P tcp–tcp-flags all syn,rst,ack,fin,urg-j DROP

# record and discard broadcast/multicast and invalid packets

$IPT-A input-i ${pub_if}-M Pkttype–pkt-type broadcast-j Log–log-prefix "broadcast"

$IPT-A input-i ${pub_if}-M Pkttype–pkt-type broadcast-j DROP

$IPT-A input-i ${pub_if}-M pkttype–pkt-type multicast-j log–log-prefix "Multicast"

$IPT-A input-i ${pub_if}-M Pkttype–pkt-type multicast-j DROP

$IPT-A input-i ${pub_if}-M state–state invalid-j log–log-prefix "INVALID"

$IPT-A input-i ${pub_if}-M state–state invalid-j DROP

# Log and block spoofing IP

$IPT-N spooflist

For IPblock in $SPOOFIP

Todo

$IPT-A Spooflist-i ${pub_if}-S $ipblock-j Log–log-prefix "spoof List block"

$IPT-A Spooflist-i ${pub_if}-S $ipblock-j DROP

Done

$IPT-I input-j spooflist

$IPT-I output-j spooflist

$IPT-I forward-j spooflist

# allow SSH to be used only from selected public IP

For IP in ${pub_ssh_only}

Do $IPT-A input-i ${pub_if}-S ${ip}-P tcp-d ${server_ip}–destination-port 22-j

$IPT-A Output-o ${pub_if}-D ${ip}-P tcp-s ${server_ip}–sport 22-j

Done

# Allow inbound ICMP ping

$IPT-A input-i ${pub_if}-P icmp–icmp-type 8-s 0/0-M state–state new,established,related-m limit–limit 30/sec-j ACCEPT

$IPT-A Output-o ${pub_if}-P icmp–icmp-type 0-d 0/0-M state–state established,related-j ACCEPT

# Allow inbound HTTP port 80

$IPT-A input-i ${pub_if}-P tcp-s 0/0–sport 1024:65535–dport 80-m state–state new,established-j

$IPT-A Output-o ${pub_if}-P tcp–sport 80-d 0/0–dport 1024:65535-m state–state established-j

# Allow outbound NTP

$IPT-A Output-o ${pub_if}-P udp–dport 123-m state–state new,established-j ACCEPT

$IPT-A input-i ${pub_if}-P udp–sport 123-m state–state established-j ACCEPT

# Allow outbound SMTP

$IPT-A Output-o ${pub_if}-P tcp–dport 25-m state–state new,established-j ACCEPT

$IPT-A input-i ${pub_if}-P tcp–sport 25-m state–state established-j ACCEPT

### here to add other rules #

###################### #www. 111cn.net

# Delete and record other packets

$IPT-A input-m limit–limit 5/m–limit-burst 7-j log–log-prefix "DEFAULT DROP"

$IPT-A input-j DROP

Exit 0

8. Control buffer Overflow Attack

Edit Nginx.conf Set the buffer size limits available to all clients:

# vi/usr/local/nginx/conf/nginx.conf

The specific settings are as follows:

# # Start:size Limits & Buffer Overflows # client_body_buffer_size 1k;client_header_buffer_size 1k;  Client_max_body_size 1k; Large_client_header_buffers 2 1k; # # End:size Limits & Buffer Overflows # #

Description

Client_body_buffer_size 1k: The default is 8k or 16k, specifying the client request principal buffer size.

Client_header_buffer_size 1k: Specifies the Headerbuffer size from the client request header, and for most requests, the 1k buffer size is sufficient, and if you customize the message header or have a larger cookie, you can increase its size.

Client_max_body_size 1k: The maximum acceptable body size in a client request, indicated by the content-length in the request header, if the size is greater than the given size, the client receives a request Entity Too Large (413) "error, if you want to upload the file through the Post method, you can set the value larger.

Large_client_header_buffers 2 1k: The maximum number and size of caches specified for a larger message header in the client request, by default, the size of a buffer is equal to the size of the page, depending on the platform may be 4 K or 8 K, if the request The end state of the connection is converted to a Hold activity (keep-alive), these buffers are freed and the 2x1k will be able to receive the URI of the 2KB data to help combat the robot attack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.