Assuming you’ve already got your reverse proxy running, in wp-config.php add the following:
/** TLS/HTTPS fixes **/// in some setups HTTP_X_FORWARDED_PROTO might contain a comma-separated list
// e.g. http,https so check for https existence.
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !==false) {
// update HTTPS server variable to always 'pretend' incoming requests were
// performed via the HTTPS protocol.
$_SERVER['HTTPS']='on';
}
I have seen several posts on how to configure SSL offloading using Nginx, but I was unable to find complete instructions for Apache. It also so happened, that I prefer Apache web server over Nginx. That fact made me create this short post.
In this post, I’d like to describe the SSL termination approach in general and provide the specific configuration for the Apache2 web server.
General approach
The idea is to set up an environment with:
Varnish with frontend on port 80 and backend on port 8080
The first website that listens to port 8080 and serves the web application (Magento 2 in this example)
Second web site listening to port 443, handling SSL and proxy passing traffic to Varnish on port 80
The following instructions are based on Ubuntu 16 and Apache 2.4.
Varnish configuration
Varnish configuration does not make too much difference here, for consistency with other components it’s important to ensure that Varnish frontend and backend are on correct ports:
An important part for VCL file (/etc/varnish/default.vcl)
Make sure apache is listening to port 8080 (/etc/apache2/ports.conf).
The second virtual host is a bit more complicated as it utilizes extra apache 2 modules, handles SSL and proxies the request.
RequestHeader set X-Forwarded-Proto "https"
ServerName localhost.com
SSLEngine On
SSLCertificateFile /etc/apache2/ssl/cert.crt
SSLCertificateKeyFile /etc/apache2/ssl/cert.key
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:80/
ProxyPassReverse / http://127.0.0.1:80/
The “X-Forwarded-Proto” header is not required for the setup to work, however, it is quite useful and may be necessary for correct work of web frameworks. It’s also known as “offloading” header.
Apache modules
As you might already notice from the virtual host configuration file that there are several mods that have to be enabled.
Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is a lightweight choice that can be used as either a web server or reverse proxy.
In this guide, we’ll discuss how to install Nginx on your Ubuntu 20.04 server, adjust the firewall, manage the Nginx process, and set up server blocks for hosting more than one domain from a single server.
Prerequisites
Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. You can learn how to configure a regular user account by following our Initial server setup guide for Ubuntu 20.04.
You will also optionally want to have registered a domain name before completing the last steps of this tutorial. To learn more about setting up a domain name with DigitalOcean, please refer to our Introduction to DigitalOcean DNS.
When you have an account available, log in as your non-root user to begin.
Step 1 – Installing Nginx
Because Nginx is available in Ubuntu’s default repositories, it is possible to install it from these repositories using the apt packaging system.
Since this is our first interaction with the apt packaging system in this session, we will update our local package index so that we have access to the most recent package listings. Afterwards, we can install nginx:
sudoapt update
sudoaptinstall nginx
After accepting the procedure, apt will install Nginx and any required dependencies to your server.
Step 2 – Adjusting the Firewall
Before testing Nginx, the firewall software needs to be adjusted to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.
List the application configurations that ufw knows how to work with by typing:
sudo ufw app list
You should get a listing of the application profiles:
Output
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
As demonstrated by the output, there are three profiles available for Nginx:
Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)
Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)
It is recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Right now, we will only need to allow traffic on port 80.
You can enable this by typing:
sudo ufw allow ‘Nginx HTTP’
You can verify the change by typing:
sudo ufw status
The output will indicated which HTTP traffic is allowed:
Output
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)
Step 3 – Checking your Web Server
At the end of the installation process, Ubuntu 20.04 starts Nginx. The web server should already be up and running.
We can check with the systemd init system to make sure the service is running by typing:
systemctl status nginx
Output
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2020-04-20 16:08:19 UTC; 3 days ago
Docs: man:nginx(8)
Main PID: 2369 (nginx)
Tasks: 2 (limit: 1153)
Memory: 3.5M
CGroup: /system.slice/nginx.service
├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─2380 nginx: worker process
As confirmed by this out, the service has started successfully. However, the best way to test this is to actually request a page from Nginx.
You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server’s IP address. If you do not know your server’s IP address, you can find it by using the icanhazip.com tool, which will give you your public IP address as received from another location on the internet:
curl -4 icanhazip.com
When you have your server’s IP address, enter it into your browser’s address bar:
http://your_server_ip
You should receive the default Nginx landing page:
If you are on this page, your server is running correctly and is ready to be managed.
Step 4 – Managing the Nginx Process
Now that you have your web server up and running, let’s review some basic management commands.
To stop your web server, type:
sudo systemctl stop nginx
To start the web server when it is stopped, type:
sudo systemctl start nginx
To stop and then start the service again, type:
sudo systemctl restart nginx
If you are only making configuration changes, Nginx can often reload without dropping connections. To do this, type:
sudo systemctl reload nginx
By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing:
sudo systemctl disable nginx
To re-enable the service to start up at boot, you can type:
sudo systemctl enable nginx
You have now learned basic management commands and should be ready to configure the site to host more than one domain.
Step 5 – Setting Up Server Blocks (Recommended)
When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name.
Nginx on Ubuntu 20.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.
Create the directory for your_domain as follows, using the -p flag to create any necessary parent directories:
sudomkdir -p /var/www/your_domain/html
Next, assign ownership of the directory with the $USER environment variable:
The permissions of your web roots should be correct if you haven’t modified your umask value, which sets default file permissions. To ensure that your permissions are correct and allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others, you can input the following command:
sudochmod -R 755 /var/www/your_domain
Next, create a sample index.html page using nano or your favorite editor:
sudonano /var/www/your_domain/html/index.html
Inside, add the following sample HTML:
/var/www/your_domain/html/index.html
<html><head><title>Welcome to your_domain!title>head><body><h1>Success! The your_domain server block is working!h1>body>html>
Save and close the file by pressing Ctrl+X to exit, then when prompted to save, Y and then Enter.
In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/your_domain:
sudonano /etc/nginx/sites-available/your_domain
Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:
Note: Nginx uses a common practice called symbolic links, or symlinks, to track which of your server blocks are enabled. Creating a symlink is like creating a shortcut on disk, so that you could later delete the shortcut from the sites-enabled directory while keeping the server block in sites-available if you wanted to enable it.
Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives (you can read more about how Nginx processes these directives here):
your_domain: Will respond to requests for your_domain and www.your_domain.
default: Will respond to any requests on port 80 that do not match the other two blocks.
To avoid a possible hash bucket memory problem that can arise from adding additional server names, it is necessary to adjust a single value in the /etc/nginx/nginx.conf file. Open the file:
sudonano /etc/nginx/nginx.conf
Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line. If you are using nano, you can quickly search for words in the file by pressing CTRL and w.
Note: Commenting out lines of code – usually by putting # at the start of a line – is another way of disabling them without needing to actually delete them. Many configuration files ship with multiple options commented out so that they can be enabled or disabled, by toggling them between active code and documentation.
Next, test to make sure that there are no syntax errors in any of your Nginx files:
sudo nginx -t
If there aren’t any problems, restart Nginx to enable your changes:
sudo systemctl restart nginx
Nginx should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like this:
Step 6 – Getting Familiar with Important Nginx Files and Directories
Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.
Content
/var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, is served out of the /var/www/html directory. This can be changed by altering Nginx configuration files.
Server Configuration
/etc/nginx: The Nginx configuration directory. All of the Nginx configuration files reside here.
/etc/nginx/nginx.conf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuration.
/etc/nginx/sites-available/: The directory where per-site server blocks can be stored. Nginx will not use the configuration files found in this directory unless they are linked to the sites-enabled directory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory.
/etc/nginx/sites-enabled/: The directory where enabled per-site server blocks are stored. Typically, these are created by linking to configuration files found in the sites-available directory.
/etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.
Server Logs
/var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise.
/var/log/nginx/error.log: Any Nginx errors will be recorded in this log.
Conclusion
Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.
Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is a lightweight choice that can be used as either a web server or reverse proxy.
In this guide, we’ll discuss how to install Nginx on your Ubuntu 20.04 server, adjust the firewall, manage the Nginx process, and set up server blocks for hosting more than one domain from a single server.
Prerequisites
Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. You can learn how to configure a regular user account by following our Initial server setup guide for Ubuntu 20.04.
You will also optionally want to have registered a domain name before completing the last steps of this tutorial. To learn more about setting up a domain name with DigitalOcean, please refer to our Introduction to DigitalOcean DNS.
When you have an account available, log in as your non-root user to begin.
Step 1 – Installing Nginx
Because Nginx is available in Ubuntu’s default repositories, it is possible to install it from these repositories using the apt packaging system.
Since this is our first interaction with the apt packaging system in this session, we will update our local package index so that we have access to the most recent package listings. Afterwards, we can install nginx:
sudoapt update
sudoaptinstall nginx
After accepting the procedure, apt will install Nginx and any required dependencies to your server.
Step 2 – Adjusting the Firewall
Before testing Nginx, the firewall software needs to be adjusted to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.
List the application configurations that ufw knows how to work with by typing:
sudo ufw app list
You should get a listing of the application profiles:
Output
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
As demonstrated by the output, there are three profiles available for Nginx:
Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)
Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)
It is recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Right now, we will only need to allow traffic on port 80.
You can enable this by typing:
sudo ufw allow ‘Nginx HTTP’
You can verify the change by typing:
sudo ufw status
The output will indicated which HTTP traffic is allowed:
Output
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)
Step 3 – Checking your Web Server
At the end of the installation process, Ubuntu 20.04 starts Nginx. The web server should already be up and running.
We can check with the systemd init system to make sure the service is running by typing:
systemctl status nginx
Output
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2020-04-20 16:08:19 UTC; 3 days ago
Docs: man:nginx(8)
Main PID: 2369 (nginx)
Tasks: 2 (limit: 1153)
Memory: 3.5M
CGroup: /system.slice/nginx.service
├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─2380 nginx: worker process
As confirmed by this out, the service has started successfully. However, the best way to test this is to actually request a page from Nginx.
You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server’s IP address. If you do not know your server’s IP address, you can find it by using the icanhazip.com tool, which will give you your public IP address as received from another location on the internet:
curl -4 icanhazip.com
When you have your server’s IP address, enter it into your browser’s address bar:
http://your_server_ip
You should receive the default Nginx landing page:
If you are on this page, your server is running correctly and is ready to be managed.
Step 4 – Managing the Nginx Process
Now that you have your web server up and running, let’s review some basic management commands.
To stop your web server, type:
sudo systemctl stop nginx
To start the web server when it is stopped, type:
sudo systemctl start nginx
To stop and then start the service again, type:
sudo systemctl restart nginx
If you are only making configuration changes, Nginx can often reload without dropping connections. To do this, type:
sudo systemctl reload nginx
By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing:
sudo systemctl disable nginx
To re-enable the service to start up at boot, you can type:
sudo systemctl enable nginx
You have now learned basic management commands and should be ready to configure the site to host more than one domain.
Step 5 – Setting Up Server Blocks (Recommended)
When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name.
Nginx on Ubuntu 20.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.
Create the directory for your_domain as follows, using the -p flag to create any necessary parent directories:
sudomkdir -p /var/www/your_domain/html
Next, assign ownership of the directory with the $USER environment variable:
The permissions of your web roots should be correct if you haven’t modified your umask value, which sets default file permissions. To ensure that your permissions are correct and allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others, you can input the following command:
sudochmod -R 755 /var/www/your_domain
Next, create a sample index.html page using nano or your favorite editor:
nano /var/www/your_domain/html/index.html
Inside, add the following sample HTML:
/var/www/your_domain/html/index.html
<html><head><title>Welcome to your_domain!title>head><body><h1>Success! The your_domain server block is working!h1>body>html>
Save and close the file by pressing Ctrl+X to exit, then when prompted to save, Y and then Enter.
In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/your_domain:
sudonano /etc/nginx/sites-available/your_domain
Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:
Note: Nginx uses a common practice called symbolic links, or symlinks, to track which of your server blocks are enabled. Creating a symlink is like creating a shortcut on disk, so that you could later delete the shortcut from the sites-enabled directory while keeping the server block in sites-available if you wanted to enable it.
Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives (you can read more about how Nginx processes these directives here):
your_domain: Will respond to requests for your_domain and www.your_domain.
default: Will respond to any requests on port 80 that do not match the other two blocks.
To avoid a possible hash bucket memory problem that can arise from adding additional server names, it is necessary to adjust a single value in the /etc/nginx/nginx.conf file. Open the file:
sudonano /etc/nginx/nginx.conf
Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line. If you are using nano, you can quickly search for words in the file by pressing CTRL and w.
Note: Commenting out lines of code – usually by putting # at the start of a line – is another way of disabling them without needing to actually delete them. Many configuration files ship with multiple options commented out so that they can be enabled or disabled, by toggling them between active code and documentation.
Next, test to make sure that there are no syntax errors in any of your Nginx files:
sudo nginx -t
If there aren’t any problems, restart Nginx to enable your changes:
sudo systemctl restart nginx
Nginx should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like this:
Step 6 – Getting Familiar with Important Nginx Files and Directories
Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.
Content
/var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, is served out of the /var/www/html directory. This can be changed by altering Nginx configuration files.
Server Configuration
/etc/nginx: The Nginx configuration directory. All of the Nginx configuration files reside here.
/etc/nginx/nginx.conf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuration.
/etc/nginx/sites-available/: The directory where per-site server blocks can be stored. Nginx will not use the configuration files found in this directory unless they are linked to the sites-enabled directory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory.
/etc/nginx/sites-enabled/: The directory where enabled per-site server blocks are stored. Typically, these are created by linking to configuration files found in the sites-available directory.
/etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.
Server Logs
/var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise.
/var/log/nginx/error.log: Any Nginx errors will be recorded in this log.
Conclusion
Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.
Nginx is open-source software for web serving, reverse proxying, caching, load balancing, media streaming, and more. In this post, I will mention few Nginx configurations which we use frequently.
server{# Standard HTTP Protocollisten80;# Standard HTTPS Protocollisten443ssl;# Listen on 80 using IPv6listen[::]:80;# Listen only on using IPv6listen[::]:80ipv6only=on;}
Access Logging
server{# Relative or full path to log fileaccess_log/path/to/file.log;# Turn 'on' or 'off'access_logon;}
Domain Name
server{# Listen to yourdomain.comserver_nameyourdomain.com;# Listen to multiple domainsserver_nameyourdomain.comwww.yourdomain.com;# Listen to all domainsserver_name*.yourdomain.com;# Listen to all top-level domainsserver_nameyourdomain.*;# Listen to unspecified Hostnames (Listens to IP address itself)server_name"";}
server{listen80;server_nameyourdomain.com;location/{proxy_passhttp://0.0.0.0:3000;# where 0.0.0.0:3000 is your application server (Ex: node.js) bound on 0.0.0.0 listening on port 3000}}
server{listen443ssl;server_nameyourdomain.com;sslon;ssl_certificate/path/to/cert.pem;ssl_certificate_key/path/to/privatekey.pem;ssl_staplingon;ssl_stapling_verifyon;ssl_trusted_certificate/path/to/fullchain.pem;ssl_protocolsTLSv1TLSv1.1TLSv1.2;ssl_connection_timeout1d;ssl_session_cacheshared:SSL:50m;add_headerStrict-Transport-Securitymax-age=15768000;}# Permanent Redirect for HTTP to HTTPSserver{listen80;server_nameyourdomain.com;return301https://$host$request_uri;}
To put inside a configuration file in /etc/nginx/conf.d/
# do not cache xmlhttp requests
map$http_x_requested_with$http_request_no_cache{default0;XMLHttpRequest1;}# do not cache requests for the following cookies
map$http_cookie$cookie_no_cache{default0;"~*wordpress_[a-f0-9]+"1;"~*wp-postpass"1;"~*wordpress_logged_in"1;"~*wordpress_no_cache"1;"~*comment_author"1;"~*woocommerce_items_in_cart"1;"~*woocommerce_cart_hash"1;"~*wptouch_switch_toogle"1;"~*comment_author_email_"1;}# do not cache requests for the following uri
map$request_uri$uri_no_cache{default0;"~*/wp-admin/"1;"~*/wp-[a-zA-Z0-9-]+.php"1;"~*/feed/"1;"~*/index.php"1;"~*/[a-z0-9_-]+-sitemap([0-9]+)?.xml"1;"~*/sitemap(_index)?.xml"1;"~*/wp-comments-popup.php"1;"~*/wp-links-opml.php"1;"~*/wp-.*.php"1;"~*/xmlrpc.php"1;}# do not cache request with args (like site.tld/index.php?id=1)
map$query_string$query_no_cache{default1;""0;}# map previous conditions with the variable $skip_cache
map$http_request_no_cache$cookie_no_cache$uri_no_cache$query_no_cache$skip_cache{default1;00000;}
Define fastcgi_cache settings
To put inside another configuration file in /etc/nginx/conf.d
server{server_namedomain.tld;access_log/var/log/nginx/domain.tld.access.log;error_log/var/log/nginx/domain.tld.error.log;root/var/www/domain.tld/htdocs;indexindex.phpindex.htmlindex.htm;# add X-fastcgi-cache header to see if requests are cached
add_headerX-fastcgi-cache$upstream_cache_status;# default try_files directive for WP 5.0+ with pretty URLs
location/{try_files$uri$uri//index.php$is_args$args;}# pass requests to fastcgi with fastcgi_cache enabled
location~\.php${try_files$uri=404;includefastcgi_params;fastcgi_passphp;fastcgi_cache_bypass$skip_cache;fastcgi_no_cache$skip_cache;fastcgi_cacheWORDPRESS;fastcgi_cache_valid20030m;}# block to purge nginx cache with nginx was built with ngx_cache_purge module
location~/purge(/.*){fastcgi_cache_purgeWORDPRESS"$scheme$request_method$host$1";access_logoff;}}
location/folder/{# The / is important!
proxy_passhttp://127.0.0.1:3000/;# The / is important!
proxy_redirectoff;proxy_set_headerHost$host;proxy_set_headerX-Real-IP$remote_addr;proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;}
Proxy keepalive for websocket
# Upstreams
upstreambackend{server127.0.0.1:3000;keepalive5;}# HTTP Server
server{server_nameyour_hostname.com;error_log/var/log/nginx/rocketchat.access.log;location/{proxy_passhttp://backend;proxy_http_version1.1;proxy_set_headerUpgrade$http_upgrade;proxy_set_headerConnection"upgrade";proxy_set_headerHost$http_host;proxy_set_headerX-Real-IP$remote_addr;proxy_set_headerX-Forward-For$proxy_add_x_forwarded_for;proxy_set_headerX-Forward-Protohttp;proxy_set_headerX-Nginx-Proxytrue;proxy_redirectoff;}}
Reverse-Proxy For Apache
server{server_namedomain.tld;access_log/var/log/nginx/domain.tld.access.log;error_log/var/log/nginx/domain.tld.error.log;root/var/www/domain.tld/htdocs;# pass requests to Apache backend
location/{proxy_passhttp://backend;}# handle static files with a fallback
location~*\.(ogg|ogv|svg|svgz|eot|otf|woff|woff2|ttf|m4a|mp4|ttf|rss|atom|jpe?g|gif|cur|heic|png|tiff|ico|zip|webm|mp3|aac|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|swf|webp)$ {add_header"Access-Control-Allow-Origin""*";access_logoff;log_not_foundoff;expiresmax;try_files$uri@fallback;}# fallback to pass requests to Apache if files are not found
location@fallback{proxy_passhttp://backend;}}
# serve WebP images if web browser support WebP
map$http_accept$webp_suffix{default"";"~*webp"".webp";}
Set conditional try_files to server WebP image :
if web browser support WebP
if WebP alternative exist
# webp rewrite rules for jpg and png images
# try to load alternative image.png.webp before image.png
location/wp-content/uploads{location~\.(png|jpe?g)${add_headerVary"Accept-Encoding";add_header"Access-Control-Allow-Origin""*";add_headerCache-Control"public,no-transform";access_logoff;log_not_foundoff;expiresmax;try_files$uri$webp_suffix$uri=404;}}
How do I install MySQL server 8.0 on CentOS 8 Linux server running on Linode and AWS cloud? How do I add and set up a new MySQL user and database account on the newly created CentOS server?
Oracle MySQL server version 8.0 is a free and open-source free database server. It is one of the most popular database system used in web apps and websites on the Internet.
Typically MySQL is part of the LAMP (Linux, Apache/Nginx, MySQL, Perl/Python/PHP) stack. Popular open-source software such as WordPress, MediaWiki, and others profoundly used by MySQL as a database storage engine. Let us see how to install MySQL server version 8.x on CentOS 8 Linux server.
First, open the terminal app and then log in to your CentOS server using the ssh command: $ ssh vivek@centos-8-ec2-box-ip
Now, update CentOS system to apply security updates and fixes on Linux system using the dnf command/yum command: $ sudo yum update ## or ##
$ sudo dnf update Sample outputs:
Luckily our CentOS 8 box comes with MySQL 8 server package. Let us search for it: $ sudo yum search mysql-server
$ sudo yum module list mysql
And we see:
Last metadata expiration check: 0:02:47 ago on Mon Nov 23 16:26:31 2020.
===================== Name Exactly Matched: mysql-server ======================
mysql-server.x86_64 : The MySQL server and related files
Next, find out version information, run: $ sudo yum info mysql-server
Here is what we see:
Last metadata expiration check: 0:02:22 ago on Mon Nov 23 16:26:31 2020.
Available Packages
Name : mysql-server
Version : 8.0.21
Release : 1.module_el8.2.0+493+63b41e36
Architecture : x86_64
Size : 22 M
Source : mysql-8.0.21-1.module_el8.2.0+493+63b41e36.src.rpm
Repository : AppStream
Summary : The MySQL server and related files
URL : http://www.mysql.com
License : GPLv2 with exceptions and LGPLv2 and BSD
Description : MySQL is a multi-user, multi-threaded SQL database server. MySQL
: is a client/server implementation consisting of a server daemon
: (mysqld) and many different client programs and libraries. This
: package contains the MySQL server and some accompanying files
: and directories.
Install it: $ sudo yum install mysql-server
Click to enlarge
Step 2 – Enabling MySQL 8 mysqld.service,server
The service name is mysqld.service, and we need to enable it using the following systemctl command: $ sudo systemctl enable mysqld.service
Confirmation displayed:
Start the service and then verify it: $ sudo systemctl start mysqld.service
$ sudo systemctl status mysqld.service
● mysqld.service - MySQL 8.0 database server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2020-11-23 16:50:14 UTC; 4s ago
Process: 551 ExecStopPost=/usr/libexec/mysql-wait-stop (code=exited, status=0/SUCCESS)
Process: 681 ExecStartPost=/usr/libexec/mysql-check-upgrade (code=exited, status=0/SUCCESS)
Process: 601 ExecStartPre=/usr/libexec/mysql-prepare-db-dir mysqld.service (code=exited, status=0/SUCCESS)
Process: 577 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited, status=0/SUCCESS)
Main PID: 637 (mysqld)
Status: "Server is operational"
Tasks: 39 (limit: 24960)
Memory: 331.0M
CGroup: /system.slice/mysqld.service
└─637 /usr/libexec/mysqld --basedir=/usr
Nov 23 16:50:13 centos-aws-mysql systemd[1]: Stopped MySQL 8.0 database server.
Nov 23 16:50:13 centos-aws-mysql systemd[1]: Starting MySQL 8.0 database server...
Nov 23 16:50:14 centos-aws-mysql systemd[1]: Started MySQL 8.0 database server.
Step 3 – Securing MySQL 8 server
All you need to do is type the following command, and it will secure MySQL 8 server installation on CentOS Linux: $ sudo mysql_secure_installation
Please set the password for root here.
New password:
Re-enter new password:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.
All done!
Step 4 – Starting/Stopping/Restarting MySQL 8 server
The syntax is: $ sudo systemctl start mysql.service
$ sudo systemctl stop mysql.service
$ sudo systemctl restart mysql.service
To view the MySQL 8 service log as follows using the journalctl command: $ sudo journalctl -u mysqld.service -xe
$ sudo tail -f /var/log/mysql/mysqld.log MySQL 8 log file sample entries:
2020-11-23T16:55:19.101316Z 0 [System] [MY-013172] [Server] Received SHUTDOWN from user . Shutting down mysqld (Version: 8.0.21).
2020-11-23T16:55:21.728819Z 0 [Warning] [MY-010909] [Server] /usr/libexec/mysqld: Forcing close of thread 10 user: 'root'.
2020-11-23T16:55:23.083389Z 0 [System] [MY-010910] [Server] /usr/libexec/mysqld: Shutdown complete (mysqld 8.0.21) Source distribution.
2020-11-23T16:56:19.225544Z 0 [System] [MY-010116] [Server] /usr/libexec/mysqld (mysqld 8.0.21) starting as process 524
2020-11-23T16:56:19.237500Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-11-23T16:56:19.562441Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-11-23T16:56:19.677202Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/lib/mysql/mysqlx.sock
2020-11-23T16:56:19.754024Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-11-23T16:56:19.754207Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2020-11-23T16:56:19.780843Z 0 [System] [MY-010931] [Server] /usr/libexec/mysqld: ready for connections. Version: '8.0.21' socket: '/var/lib/mysql/mysql.sock' port: 3306 Source distribution.
Step 5 – Testing MySQL 8 installation
So far, so good. You learned how to install, set up, secure, and start/stop the MySQL 8 on CentOS 8 Linux cloud server. It is time to log in as a
mysql root user. The syntax is: $ mysql -u root -p
$ mysql -u USER -h host -p
$ mysql -u USER -h host -p mysql
Let us type a few SQL commands at the mysql> prompt: STATUS;
SHOW VARIABLES LIKE "%version%";
quit
Step 6 – Creating a new MySQL 8 database and user account with password
Let create a new database called ‘spacedb‘, type at the mysql> prompt: CREATE DATABASE spacedb;
Next, we are going to create a new user named ‘mars‘ for our database called ‘spacedb’ as follows: CREATE USER 'mars'@'%' IDENTIFIED BY 'User_Password_Here';
Finally, give permissions: GRANT SELECT, INSERT, UPDATE, DELETE ON spacedb.* TO 'mars'@'%';
Of course, we can grant ALL PRIVILEGES too as follows: GRANT ALL PRIVILEGES ON spacedb.* TO 'mars'@'%';
See MySQL 8 users and their grants/permissions as follows: SELECT user,host FROM mysql.user;
SHOW GRANTS for mars;
quit
Test new user settings and DB as follows: mysql -u mars -p spacedb
mysql -u mars -h localhost -p spacedb
Where,
-u mars; : User name for login
-h localhost : Connect to server named localhost
-p : Prompt for password
spacedb : Connect to database named spacedb
Step 7 – Configuring MySQL 8 server on a CentOS 8
Let us see default config file using the cat command: # cat /etc/my.cnf.d/mysql-server.cnf Config:
WARNING: See MySQL documentation for a detailed explanation for tuning options as to each server and set up is unique. Do not set up values blindly. I provide them as a starting point for optimizing MySQL 8 installation and values depending upon available RAM, CPU cores, server load and other circumstances.
Step 8 – Firewall configuration to open MySQL server TCP port 3306
Are you using MySQL 8 server remotely? Do you have Apache/Nginx/PHP/Python/Perl app on another server? Then open port for everyone: $ sudo firewall-cmd --zone=public --add-service=mysql --permanent
Only allow access from 192.168.1.0/24 CIDR: $ sudo firewall-cmd \
--add-rich-rule 'rule family="ipv4" \
source address="192.168.1.0/24" \
service name="mysql" accept' --permanent
The above is fine grained firewalld access rules to restrict access to MySQL 8 server to VLAN users only. See how to set up a firewall using FirewallD on CentOS 8 Linux for more info.
Conclusion
And there you have it, Oracle MySQL server version 8.x set up and running correctly on a CentOS Linux 8 server with Firewalld config. Further, you learned how to add a new database, user, and password for your project including MySQL 8 server tuning options.
Create a new virtual machine and install the CentOS to the virtual machine. During the CentOS installation, select Workstation as Base Environment, select Container Management, Development Tools and Graphical Administration Tools as Additional software for Selected Environment. Use http://mirror.centos.org/centos/8/BaseOS/x86_64/os/ as the installation source.
After installing the CentOS, execute the following commands to get the required libraries to create applications for handling compiled objects.
dnf update
dnf -y install elfutils-libelf-devel
Insert the ISO of VirtualBox Guest Additions to the virtual machine, and then install it.
Use the following command, with oracle user, to edit the crontab file.
crontab -e
Put the following cron job in the first line of crontab file, then press the keys :wq to save and exit.
@reboot /home/oracle/scripts/cron.sh
Healthcheck
Login as oracle user and then execute the following commands one-by-one.
sqlplus /nolog
conn / as sysdba;select* from v$version;
show pdbs;
Create New User and Tablespace
Login as Sysdba with SqlPlus.
sqlplus / as sysdba
Update the seesion setting _ORACLE_SCRIPT to true to allow common user comes without c## as prefix.
ALTER SESSION SET"_ORACLE_SCRIPT"=true;
Create a new tablespace with an automatic extensible size 100MB, maximum 10G in size.
-- DROP TABLESPACE my_tablespace INCLUDING CONTENTS AND DATAFILES;-- Location of the dat file: /u01/app/oracle/product/19.3.0/dbhome_1/dbs/my_tablespace.dat-- SELECT tablespace_name, block_size, max_size, status FROM DBA_TABLESPACES;CREATETABLESPACEmy_tablespace
DATAFILE 'my_tablespace.dat'
SIZE 100M
AUTOEXTEND ON
NEXT 32M MAXSIZE 10G
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO
;
SELECT FILE_ID, FILE_NAME, TABLESPACE_NAME, AUTOEXTENSIBLE, INCREMENT_BY
FROM DBA_DATA_FILES ORDER BY FILE_ID DESC;
[Optional] Update the password life time from 180 days (default) to unlimited.
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
Create a new user.
-- ALTER SESSION SET "_ORACLE_SCRIPT"=true;-- DROP USER newuser CASCADE;CREATEUSERnewuser IDENTIFIED BY "P@ssw0rd" DEFAULT TABLESPACE my_tablespace;
Grant permissions to the new user.
-- REVOKE CREATE SESSION FROM newuser;-- REVOKE CREATE TABLE FROM newuser;-- REVOKE CREATE VIEW FROM newuser;-- REVOKE CREATE ANY TRIGGER FROM newuser;-- REVOKE CREATE ANY PROCEDURE FROM newuser;-- REVOKE CREATE SEQUENCE FROM newuser;-- REVOKE CREATE SYNONYM FROM newuser;GRANT CREATE SESSION TO newuser;
GRANT CREATE TABLE TO newuser;
GRANT CREATE VIEW TO newuser;
GRANT CREATE ANY TRIGGER TO newuser;
GRANT CREATE ANY PROCEDURE TO newuser;
GRANT CREATE SEQUENCE TO newuser;
GRANT CREATE SYNONYM TO newuser;
ALTERUSER newuser QUOTA UNLIMITED ON my_tablespace;
ISD ofron suport IT me staf të kualifikuar të gatshëm 24×7. Suporti ynë është i disponueshëm online, offline, remote, offsite dhe përmes manualeve të përdorimit dhe të administrimit. Suporti i ISD ofrohet në forma të ndryshme: të herëpashershëm, me kontratë të thjeshtë dhe me kontratë profesionale.