Showing posts with label Nginx. Show all posts
Showing posts with label Nginx. Show all posts

Tuesday, September 27, 2022

Setup Nginx as a reverse proxy for multiple tomcat application with SSL

Description: Here I have explain, How to setup tomcat, deploy multiple application and setup nginx as reverse proxy for tomcat application. 

Setup:

  • Install tomcat on port 8080 with 2 sample application
  • Install Nginx on port 80 and 443 to serve as a reverse proxy
  • 34.222.157.147 Public IP address of the machine 
Install Tomcat on Ubuntu 22: 

Install java for tomcat, first we are going to install java for tomcat

# apt install openjdk-11-jdk

Verify the java version after  installation 

# java --version

Install tomcat after validating the java 

# apt install tomcat9 tomcat9-admin

After installation verify the port number listening. You can get port 8080 [default port of tomcat] in list

# netstat -tnlp









Make necessary security changes for allow port 8080 from out side

After installation, set user credentials for admin url. To set the credentials open tomcat-users.xml file and modify as follow. Here we have set admin user with password 'admin'

<tomcat-users> <role rolename="manager-gui" /> <user username="manager" password="admin" roles="manager-gui" /> <role rolename="admin-gui" /> <user username="admin" password="admin" roles="manager-gui,admin-gui" /> </tomcat-users>

After tomcat application, I am going to setup 2 sample application with below name 

/SampleWebApp ==   http://34.222.157.147:8080/SampleWebApp
/sample                ==   http://34.222.157.147:8080/sample


So both the url accessible directly, Now I am installing nginx and configure it as proxy for both the url with self signed SSL. 

Install and configure Nginx

# apt install nginx
# systemctl start nginx
# systemctl enable nginx

After installation of nginx, configuring 2 virtual host for each application 

  • application1.local  ==  http://34.222.157.147:8080/SampleWebApp
  • application2.local  ==  http://34.222.157.147:8080/sample
To create the vhost file navigate to /etc/nginx/conf.d and create application1.conf  for application1.local site as follow 


server { listen 80; server_name application1.local; } server { listen 443 http2 ssl; server_name application1.local; ssl_certificate /etc/ssl/application1/application1.crt; ssl_certificate_key /etc/ssl/application1/application1.key; access_log /var/log/nginx/application1-access.log; error_log /var/log/nginx/application1-error.log; location = / { return 301 https://application1.local/SampleWebApp/; } location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; } }

Now create vhost file on /etc/nginx/conf.d path with application2.conf file name for application2.local site as follow

server { listen 80; server_name application2.local; } server { listen 443 http2 ssl; server_name application2.local; ssl_certificate /etc/ssl/application2/application2.crt; ssl_certificate_key /etc/ssl/application2/application2.key; access_log /var/log/nginx/application2-access.log; error_log /var/log/nginx/application2-error.log; location = / { return 301 https://application2.local/sample/; } location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; } }

After setting up both the vhost, need to setup either self signed or upload purchased SSL and upload to respective location. 

To apply the changes restart the nginx service and verify by browse both the url on browser. Both the application will redirect to its url with application path as follow

https://application1.local/













https://application2.local/



Wednesday, February 9, 2022

Integrate Varnish Cache With Magento

 Description: Here I have explained, How to install and Integrate Varnish Cache with Magento


Install Varnish Cache: 

Explore all the version of varnish in below URL

https://packagecloud.io/varnishcache

Select the require version, it provide script to install as per OS details 

# apt-get install apt-transport-https

# curl https://repo.varnish-cache.org/GPG-key.txt | apt-key add -

# echo "deb https://repo.varnish-cache.org/ubuntu/ trusty varnish-4.1" \ 

>      >> /etc/apt/sources.list.d/varnish-cache.list

# apt update

# apt-get install varnish

# varnishd -V


Change Default Port of Web server:

Here, I am split my configuration in two file, One file for site configuration and another proxy configuration file for varnish. Change default web server from 80 to 8080. 

Note: Before integrate varnish, Change the Magento mode to Developer mode from production using below command

$ php bin/magento deploy:mode:set developer

Files:
magentotestlab.conf -- Site configuration file

upstream fastcgi_backend { server unix:/run/php/php7.3-fpm.sock; } server { listen 8080; listen [::]:8080; server_name magentotestlab.com; access_log /var/log/nginx/magentotestlab-access.log; error_log /var/log/nginx/magentotestlab-error.log; set $MAGE_ROOT /var/www/magento2; set $MAGE_MODE developer; include /var/www/magento2/nginx.conf.sample; }



web-proxy.conf -- Site Proxy configuration file in which we define redirect request to varnish cache
server { listen 80 reuseport; server_name magentotestlab.com; return 301 https://$server_name$request_uri; } server{ listen 443 ssl http2; server_name magentotestlab.com; ssl_certificate /home/ssl/magentotestlab.crt; ssl_certificate_key /home/ssl/magentotestlab.key; access_log /var/log/nginx/www.kingstonkrafts.com-access.log; error_log /var/log/nginx/www.kingstonkrafts.com-error.log notice; location / { proxy_pass http://127.0.0.1:6081; #To Varnish # proxy_pass http://127.0.0.1:8080; #To Vhost proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Port 443; } }


Integrate Varnish in Magento 


Open Magento Admin and navigate to Stores -> Configuration -> Advanced -> System -> Full Page Cache and change the as follow and save config


After filled all the details download VCL for respective version [Like We have implement Varnish 6] 

Backup the existing configuration file and upload it to /etc/varnish/default.vcl

After Upload default.vcl change the path for health_check.php  as follow


import std; # The minimal Varnish version is 6.0 # For SSL offloading, pass the following header in your proxy server or load balancer: 'X-Forwarded-Proto: https' backend default { .host = "127.0.0.1"; .port = "8080"; .first_byte_timeout = 600s; .probe = { .url = "/health_check.php"; .timeout = 2s; .interval = 5s; .window = 10; .threshold = 5; } } ### Add IP Forwarding above 2nd health_check.php define line # IP FORWARDING if (req.restarts == 0) { if (req.http.X-Forwarded-For) { std.collect(req.http.x-forwarded-for); set req.http.X-Forwarded-For = regsub(req.http.X-Forwarded-For, "^([^,]+),?.*$", "\1"); } else { set req.http.X-Forwarded-For = 1; } }

Open varnish service configuration and add below configuration to optimise varnish service configuration Comment existing ExecStart line and add below configuration

# vi /etc/systemd/system/multi-user.target.wants/varnish.service
ExecStart=/usr/sbin/varnishd \ -a :6081 \ -a localhost:8443,PROXY \ -p feature=+http2 \ -f /etc/varnish/default.vcl \ -p thread_pool_add_delay=2 \ -p thread_pools=2 \ -p thread_pool_min=400 \ -p thread_pool_max=4000 \ -p http_resp_hdr_len=131072 \ -p http_resp_size=163840 \ -p nuke_limit=1000 \ -p workspace_client=256k \ -p workspace_backend=256k \ -s malloc,512m ExecReload=/usr/sbin/varnishreload

After add above configuration reload the daemon 

# systemctl daemon-reload

After change the configuration from Magento Frontend also changed using CLI using below command

php bin/magento setup:config:set --http-cache-hosts=127.0.0.1:6081 php bin/magento config:show --scope=default --scope-code=0 system/full_page_cache/caching_application Verify the out put from above command it should be 2. If not you can change it using below command php bin/magento config:set --scope=default --scope-code=0 system/full_page_cache/caching_application 2



Restart Nginx service after change 
# systemctl restart nginx

Verification: To verify the cache browse the URL, Inspect the page and navigate to Network. Under Network click on any page 

You will get "x-magento-cache-debug : HIT" 


Also you can verify by make sure /magento_root/var/page_cache directory is empty. Remove the files from the path and then tried to access page again. If no file generated then it successfully integrated.



Monday, February 7, 2022

Integrate Redis with Magento 2

 Description: Here I have explained, How to install and Integrate Redis with Magento.

Install Redis using apt command 

# apt-get install redis

After installation start and enable redis service 

# systemctl start redis

#systemctl enable redis

# systemctl status redis


Verify the installation using redis-cli command 



We can integrate redis with magento 2 ways, 

1> Edit the  configuration similar to the following to app/etc/env.php

'cache' => array( 'frontend' => array( // Default Cache 'default' => array( 'backend' => 'Cm_Cache_Backend_Redis', 'backend_options' => array( 'server' => '127.0.0.1', 'database' => '0', 'port' => '6379' ), ), // Full page cache 'page_cache' => array( 'backend' => 'Cm_Cache_Backend_Redis', 'backend_options' => array( 'server' => '127.0.0.1', 'port' => '6379', 'database' => '1', 'compress_data' => '0' ) ) ) ),

2> Also configure same using command line as follow

# php bin/magento setup:config:set --cache-backend=redis --cache-backend-redis-server=127.0.0.1 --cache-backend-redis-db=10 --page-cache=redis --page-cache-redis-server=127.0.0.1 --page-cache-redis-db=11 --session-save=redis --session-save-redis-host=127.0.0.1 --session-save-redis-log-level=3 --session-save-redis-db=12

Install Magento 2 with Nginx, Self signed SSL, MariaDB 10.x, PHP 7.3 on Ubuntu 20

 Description: Here I have explained, How to install Magento 2 with Nginx, Self signed SSL, MariaDB 10.x, PHP 7.3 on Ubuntu 20

  • Before start the installation Update the packages 
# apt update 



  • Install Nginx using apt command 
# apt install nginx 



  • Start and Enable Nginx service. Check the Nginx service status
# systemctl start nginx
# systemctl enable nginx 
# systemctl status nginx 


  • Install and configure PHP-FPm 7.3
  • Before install PHP add repository for same 
sudo apt install software-properties-common
add-apt-repository ppa:ondrej/php



  • Install PHP from PPA repository 
# apt install php7.3-fpm php7.3-common php7.3-curl php7.3-cli php7.3-mysql php7.3-gd php7.3-xml php7.3-json php7.3-intl php-pear php7.3-dev php7.3-common php7.3-mbstring php7.3-zip php7.3-soap php7.3-bcmath php7.3-opcache -y



 
  • Update PHP FPm and CLI configuration as follow
Open /etc/php/7.3/fpm/php.ini and vi /etc/php/7.3/cli/php.ini configuration file and update the parameters as follow:

date.timezone = Asia/Kolkata memory_limit = 2G max_execution_time = 1800 zlib.output_compression = On cgi.fix_pathinfo = 1 opcache.enable=1 opcache.save_comments = 1

  • Start and Enable php-fpm service. Also check php-fpm status
# systemctl start php7.3-fpm
# systemctl enable php7.3-fpm
# systemctl status php7.3-fpm 

  • Install and Configure MariaDB
# apt install mariadb-server

After installation start and enable mariadb service 

# systemctl start mariadb
# systemctl enable mariadb

Configure Mariadb

# mysql_secure_installation 

Set a root password? [Y/n] Y Remove anonymous users? [Y/n] Y Disallow root login remotely? [Y/n] Y Remove test database and access to it? [Y/n] Y Reload privilege tables now? [Y/n] Y

Login into mysql using root user and create database and user with privileges

# mysql -u root -p 

create database magentodb; create user magentouser@'localhost' identified by 'magentopassdb'; grant all privileges on magentodb.* to magentouser@'localhost'; flush privileges;

Install composer and verify the version

# apt install composer -y
# composer --version 

Download and Install Magento 2 

# cd /var/www   ### You  can change to path as per your requirement ###
# wget -q https://github.com/magento/magento2/archive/2.3.5.tar.gz
# tar -xf 2.3.5.tar.gz
# mv magento2-2.3.5/ magento2
# cd /var/www/magento2/
# composer install


# chown -R www-data:www-data /var/www/magento2

Setup SSL for Magento Site: Here I am going to create self signed certificate and use it for same

  • Generate Self Signed SSL in ubuntu [In this example I will use magentotestlab.com as URL]
# mkdir /home/ssl
# cd /home/ssl
#  openssl req -newkey rsa:4096 -x509 -sha256 -days 3650 -nodes -out magentotestlab.crt -keyout magentotestlab.key


Country Name (2 letter code) [AU]:IN State or Province Name (full name) [Some-State]:GJ Locality Name (eg, city) []:AH Organization Name (eg, company) [Internet Widgits Pty Ltd]:magentotestlab pvt ltd Organizational Unit Name (eg, section) []:IT Common Name (e.g. server FQDN or YOUR name) []:magentotestlab.com Email Address []:

Note: After filled all the details certificate and key file will be created on same path

Setup Nginx Virtual Host for Magento2 

  • Open the Nginx configuration directory and create configuration for Magento
# cd /etc/nginx/sites-available/
# vi magentotestlab                    ### Create the configuration and paste as follow ###

upstream fastcgi_backend { server unix:/run/php/php7.3-fpm.sock; } server { listen 80; listen [::]:80; server_name magentotestlab.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name magentotestlab.com; ssl_certificate /home/ssl/magentotestlab.crt; ssl_certificate_key /home/ssl/magentotestlab.key; set $MAGE_ROOT /var/www/magento2; set $MAGE_MODE developer; include /var/www/magento2/nginx.conf.sample; }
f
Remove Default host configuration from /etc/nginx/sites-available and /etc/nginx/sites-enable 
After remove the configuration link the configuration using ln  command 

# ln -s /etc/nginx/sites-available/magentotestlab /etc/nginx/sites-enabled
# nginx -t   ### Verify the configuration after setup ###


# systemctl restart nginx

Magento Post Installation Task 

Browse the URL and complete the task 

https://magentotestlab.com/


First step is to check the readiness 



Give Database and User details to connect DB



URL and Admin URL Details


Store Configuration Details 


Create Admin User for Magento 


Install Magento








Once the installation will completed you will receive Screen as follow



Troubleshooting:

Too Many Redirection error in Admin Page 
  • After installation some time Admin page showing error like too many redirection 

  • To resolve this redirection issue navigate to installation path /var/www/magento2 and run the following commands
# cd /var/www/magento2/
# bin/magento config:set web/secure/use_in_adminhtml 1
# php bin/magento cache:clean


  • Now try to reopen the admin url 



Setup Cron in Magento: After setup Magento Need to setup default cron job for Magento 

Navigate to Path /var/www/magento2
# cd /var/www/magento2
# bin/magento cron:install --force     ### Install cron job ### 


Verify the cron by using crontab -l  command 



















Monday, June 22, 2020

Setup Virtual Host [Server Blocks] in Nginx

Description: Here I have explained how to Setup Virtual Host [Server Blocks] in Nginx

Server Blocks, often referred to as Nginx virtual host are a feature of the Nginx web server that allows you to host multiple websites on one server. As opposed to setting up and configuring a server for each domain, hosting a number of websites on a single machine saves both time and money.

Procedure: 

Create Directory Structure: To host multiple site on Nginx need to create individual directory structure to store data. In example I have created 2 site virtual host under /var/www directory

# mkdir -p /var/www/site1.com/html
# mkdir -p /var/www/site2.com/html

 Change Permission on directory: Change ownership on both site directories using chown command

# chown -R $user1.$user1 /var/www/site1.com/html
# chown -R $user2.$user2 /var/www/site2.com/html
# chmod -R 755 /var/www

Create index.html in both Directory: Create index.html file on both site directory respectively.

Setup Environment for Server Block: Before setup server block need to create 2 directory for setup.
  • Sites-available : Directory store server blocks 
  • Sites-enable : Directory which tell Nginx to publish and block share content
Open Nginx configuration and modify file

vi /etc/nginx/nginx.config [ Inside http block add following two lines]
include /etc/nginx/sites-enabled/*.conf
server_names_hash_bucket_size 64;

nginx configuration file


First line to check sites-enabled directory and second line for increase memory is reserved for examine multiple domain name.

After made changes run below command to verify the configuration
# nginx -t 

If syntax is OK then test was successful as in image.

testing nginx configuration with output that the test is sucessful

Create Virtual Host for the first website with cp and make a copy exact copy of file

# cp /etc/nginx/conf.d/default.conf /etc/nginx/sites-available/site1.com.conf

Open configuration file using vi editor

# vi /etc/nginx/sites-available/site1.com.conf

cloned nginx default configuration file displayed


You need to edit below 3 lines in configuration 

        server name site1.com www.site1.com;

        root /var/www/site1.com/html;

        try_files $uri $uri/ =404;

Same configuration you need to done for site2 just need to change name.

Enable Site configuration or Server block: To enable configuration need to link site available with site enable. 

# ln -s /etc/nginx/sites-available/site1.com.conf   /etc/nginx/sites-enabled/site1.com.conf

Restart Nginx Service:

# systemctl restart nginx 

# vi  /etc/hosts

ip_address site1.com
ip_address site2.com

Verify Server Blocks Setup

http://site1.com

http://site2.com 






Sunday, June 21, 2020

How to Install Nginx on Centos 7

Description: Here I have explained how to install and configure Nginx on Centos 7.

Procedure: Nginx (pronounced Engine X) is popular web server with good performance and it is alternate of Apache web server. Nginx also works as load balancer, reverse proxy and standard mail server.

Prerequisites:
  • Centos 7 server
  • Root privileges
  • Selinux setup properly
Update Repository Package List

# yum -y update

Install Extra Packages for Enterprise Linux [EPEL]

# yum install -y epel-release

Install Nginx 

# yum install -y nginx 

Start and Enable Nginx Service

# systemctl start nginx
# systemctl enable nginx

Note: If you have already install and running apache/ http, Disable it before install nginx

Enable port from firewall 

# firewall-cmd  --zone=public --permanent --add-service=http

# firewall-cmd  --zone=public --permanent --add-service=https

Verify Nginx by browse your IP Address in Browser.
http://IP_ADDRESS