Month: November 2017

  • How to install PhpMyAdmin + Nginx in Mac OS X

    How to install PhpMyAdmin + Nginx in Mac OS X

    In previous post I’ve talked about installing MySQL in Mac OS X.

    Today I want to talk about PhpMyAdmin. Tool which help work with MySQL databases.

    Here steps how to install it and configure under Nginx webserver.

    1. Create virtualhost for PhpMyAdmin.

    Create /usr/local/etc/nginx/sites-available/phpmyadmin file with next content

    server {
        listen   80; 
    
        server_name  phpmyadmin;
        
        root       /var/www/phpmyadmin/;
    
        index index.php index.html index.htm;
     
        access_log  /usr/local/etc/nginx/logs/phpmyadmin.access.log;
        error_log  /usr/local/etc/nginx/logs/phpmyadmin.error.log;
     
        location ~ \.php$ {
            try_files      $uri = 404;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    
        error_page  404     /404.html;
        error_page  403     /403.html;
    }

    Edit hosts for PhpMyAdmin

    Open /etc/hosts file and add next line

    127.0.0.1	phpmyadmin

    /etc/hosts file should looks like this:

    ##
    # Host Database
    #
    # localhost is used to configure the loopback interface
    # when the system is booting.  Do not change this entry.
    ##
    127.0.0.1	localhost
    127.0.0.1	phpmyadmin
    255.255.255.255	broadcasthost
    ::1             localhost

    Make symbolic link to sites-avalable/phpmyadmin into sites-enabled

    sudo ln -s /usr/local/etc/nginx/sites-available/phpmyadmin /usr/local/etc/nginx/sites-enabled/phpmyadmin

    Save files and restart Nginx

    sudo nginx -s stop
    sudo nginx

    2. Download PhpMyAdmin

    Link for downloading https://www.phpmyadmin.net/downloads/

    3. Put PhpMyAdmin into Nginx document root

    Unzip phpmyadmin archive into /var/www directory

    cd <folder with downloadded zip>
    unzip phpMyAdmin-4.7.5-all-languages.zip -d /var/www

    Rename /var/www/phpMyAdmin-4.7.5-all-languages into /var/www/phpmyadmin

    cd /var/www/
    mv phpMyAdmin-4.7.5-all-languages phpmyadmin

    4. Launch/restart nginx and start php-fpm

    sudo nginx -s stop
    sudo nginx
    sudo brew services start php71 
    

    5. Test phpmyadmin VirtualHost

    curl -IL http://phpmyadmin

    Output should be like this:

    HTTP/1.1 200 OK
    Server: nginx/1.12.1
    Date: Sun, 26 Nov 2017 22:12:23 GMT
    Content-Type: text/html; charset=utf-8
    Connection: keep-alive
    X-Powered-By: PHP/7.1.11
    Set-Cookie: pmaCookieVer=5; expires=Tue, 26-Dec-2017 22:12:22 GMT; Max-Age=2592000; path=/; HttpOnly
    Set-Cookie: pma_lang=en; expires=Tue, 26-Dec-2017 22:12:23 GMT; Max-Age=2592000; path=/; HttpOnly
    Set-Cookie: pma_collation_connection=utf8mb4_unicode_ci; expires=Tue, 26-Dec-2017 22:12:23 GMT; Max-Age=2592000; path=/; HttpOnly
    Set-Cookie: phpMyAdmin=c3acgrslgm88jlmvl2ovnoh2eq; path=/; HttpOnly
    X-ob_mode: 1
    X-Frame-Options: DENY
    Referrer-Policy: no-referrer
    Content-Security-Policy: default-src 'self' ;script-src 'self' 'unsafe-inline' 'unsafe-eval' ;;style-src 'self' 'unsafe-inline' ;img-src 'self' data:  *.tile.openstreetmap.org;
    X-Content-Security-Policy: default-src 'self' ;options inline-script eval-script;referrer no-referrer;img-src 'self' data:  *.tile.openstreetmap.org;
    X-WebKit-CSP: default-src 'self' ;script-src 'self'  'unsafe-inline' 'unsafe-eval';referrer no-referrer;style-src 'self' 'unsafe-inline' ;img-src 'self' data:  *.tile.openstreetmap.org;
    X-XSS-Protection: 1; mode=block
    X-Content-Type-Options: nosniff
    X-Permitted-Cross-Domain-Policies: none
    X-Robots-Tag: noindex, nofollow
    Expires: Sun, 26 Nov 2017 22:12:23 +0000
    Cache-Control: no-store, no-cache, must-revalidate,  pre-check=0, post-check=0, max-age=0
    Pragma: no-cache
    Last-Modified: Sun, 26 Nov 2017 22:12:23 +0000
    Vary: Accept-Encoding

    6. Test PhpMyAdmin in browser

    Open http://phpmyadmin in your browser. You should see next page:

    7. Login into PhpMyAdmin.

    Username: root
    Password: Which you have created for ROOT MySQL user during MySQL installation process.
    You will see next page:

     

    PhpMyAdmin installed. Happy codding!

  • Nginx + MySQL configurations

    Nginx + MySQL configurations

    Here is instructions how to install MySQL and PhpMyAdmin on Mac OS X

    1. Download and install DMG file.

    Link for downloading : https://dev.mysql.com/downloads/mysql/

    2. Installer will generate temporary root password. Save it in text file for next steps.

    3. Add /usr/local/mysql/bin to PATH

    If you use ZSH open ~/.zshrc file and add

    export PATH=/usr/local/mysql/bin:$PATH

    at the end of file. Save this file and restart all Terminal windows.

    4. Change MySQL root password

    mysqladmin -u root -p password root

    5. start MySQL service

    Open SystemPreferences and click on MySQL preferences.

    Click on “Start MySQL Server” and put tick on “Automatically Start MySQL Server on Startup”

    6. Check mysql from Terminal

    Open Terminal and run. Enter password which you have setup in step number 4.

    mysql -uroot -p

    You should see output like this:

    ➜  ~ mysql -uroot -p                       
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 123
    Server version: 5.7.20 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql>

    To exit from MySQL console type exit and hit ENTER

    You have installed MySQL.

    To make work with MySQL more comfortable I suggest to install PhpMyAdmin.

    Next post will be about it : https://www.hrupin.com/2017/11/how-to-install-phpmyadmin-nginx-in-mac-os-x

  • How to add Public Key Authentication for Ubuntu 16.04 server

    How to add Public Key Authentication for Ubuntu 16.04 server

    For better security we should use public key authentication on the server.

    Here is steps how to do it.

    1. Generate SSH key pair on your local computer.

    Skip if you already have ssh key pair in your local computer

    ssh-keygen

    Output:

    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/igor/.ssh/id_rsa):

    Hit ENTER and enter passphrase for your SSH key pair. Full output should be like this:

    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/igor/.ssh/id_rsa): 
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in /home/igor/.ssh/id_rsa.
    Your public key has been saved in /home/igor/.ssh/id_rsa.pub.
    The key fingerprint is:
    SHA256:agKodBlKuZFsGd/KGdoZYUeUjdsiyrbZy3jTctp9Q/s igor@ubuntu-server
    The key's randomart image is:
    +---[RSA 2048]----+
    |oo=.             |
    |.=*.o            |
    | O= oo           |
    |+oO.X            |
    |==oO    S        |
    |+o..   . .       |
    |o + o o . .      |
    | oo=.=.  +       |
    | .+.*. .. oE     |
    +----[SHA256]-----+

    Now you have SSH key pair on your local computer.

    2. Login to your server as root user and create new user.

    This step can be skipped if you already have user on your server

    ssh root@your_server_ip

    Output:

    The authenticity of host '45.55.152.45 (45.55.152.45)' can't be established.
    ECDSA key fingerprint is SHA256:+oRtSBmByAohvrz2o7J7Uuaf+bqTHpDt0Rm+JAj05qaQ.
    Are you sure you want to continue connecting (yes/no)?

    Type YES and continue connecting to your server

    Create new user. I will create user ‘igor’

    adduser igor

    You will be asked about Full name, Room name, phone numbers, etc. After you will be asked about information correctness. Hit ‘y‘ if all is correct.
    Sure this steps can be skipped.

    I’ve entered full info. So, my output is here. Your output should be like this:

    Adding user `igor' ...
    Adding new group `igor' (1000) ...
    Adding new user `igor' (1000) with group `igor' ...
    Creating home directory `/home/igor' ...
    Copying files from `/etc/skel' ...
    Enter new UNIX password: 
    Retype new UNIX password: 
    passwd: password updated successfully
    Changing the user information for igor
    Enter the new value, or press ENTER for the default
    	Full Name []: Igor Khrupin
    	Room Number []: 43
    	Work Phone []: +48790865345
    	Home Phone []: +48790865124
    	Other []: 
    Is the information correct? [Y/n] y

    You just have created new user in your server

    3. Add Root Privileges for your new user

    This step can be skipped if you already added root privileges for your user

    usermod -aG sudo igor

    Now your user able to run commands with sudo

    4. Add Public Key Authentication for your server

    There 2 ways how to do it. One using just one command. Second one is manually.

    Method 1. Using ssh-copy-id

    Just run next command on your local computer

    ssh-copy-id user@server_ip

    In my case command is:

    ssh-copy-id igor@45.51.151.45

    ssh-copy-id will do all for you. You just need enter password for your server’s user.
    Full output should be like this:

    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/igor/.ssh/id_rsa.pub"
    /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
    /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
    igor@45.51.151.45's password: 
    
    Number of key(s) added:        1
    
    Now try logging into the machine, with:   "ssh 'igor@45.51.151.45'"
    and check to make sure that only the key(s) you wanted were added.
    Method 2. Manually

    Add your PUBLIC key into~/.ssh/authorized_keys file on your server. First you need go to your local computer and copy this key into clipboard.
    I’ve showed my key into output and copy it from there.

    cat ~/.ssh/id_rsa.pub

    My output with SSH public key here. Your should be like this.

    ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU
    GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3
    Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA
    t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En
    mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx
    NrRFi9wrf+M7Q== igor@hrupin.com

    Copy it into clipboard.

    Login to your server as root and temporary switch to your user.
    I’m switching to my user ‘igor’

    su - igor

    Create ~/.ssh dir on your server if you don’t have it and change access rights for it

    mkdir ~/.ssh
    chmod 700 ~/.ssh

    Create ~/.ssh/authorized_keys file on your server if you don’t have it. Edit this file.

    nano ~/.ssh/authorized_keys

    Paste your PUBLIC ssh key into ~/.ssh/authorized_keys and save file.
    To do it in nano you need hit Command+X for Mac OS or CTRL-X for Windows after hit Y and ENTER

    5. Disable Password Authentication (Recommended)

    Now your new user can use SSH keys to log in.
    To make more better security you need disable password-only authentication.
    After this your server will have public key authentication only.

    Edit SSH daemon configuration using nano. It can be done using root or user with sudo rights.

    command for root:

    nano /etc/ssh/sshd_config

    command for user with root rights

    sudo nano /etc/ssh/sshd_config

    Find  PasswordAuthentication, uncomment it by deleting the #, then change its value to “no“. After it line should looks like this:

    PasswordAuthentication no

    Also ensure that you have

    PubkeyAuthentication yes
    ChallengeResponseAuthentication no

    Save file by hitting Command+X for Mac OS or CTRL-X for Windows after hit Y and ENTER

    Restart SSH Daemon

    Command for root:

    systemctl reload sshd

    Or for user with sudo rights

    sudo systemctl reload sshd

    That’s all your server is done. Let’s try how it works.

    Try to connect to your server using SSH.

    ssh user@your_server_ip

    In my case will be next:

    ssh igor@45.51.151.45

    Then you should see next output:

    ➜  ~ ssh igor@45.51.151.45
    Enter passphrase for key '/Users/igor/.ssh/id_rsa':

    Enter passphrase from YOUR COMPUTER‘s ssh key.
    If all is ok you will get access into your server. Like this:

    ➜  ~ ssh igor@45.51.151.45
    Enter passphrase for key '/Users/igor/.ssh/id_rsa': 
    Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-101-generic x86_64)
    
     * Documentation:  https://help.ubuntu.com
     * Management:     https://landscape.canonical.com
     * Support:        https://ubuntu.com/advantage
    
      Get cloud support with Ubuntu Advantage Cloud Guest:
        http://www.ubuntu.com/business/services/cloud
    
    0 packages can be updated.
    0 updates are security updates.
    
    
    Last login: Sat Nov 25 10:57:24 2017 from 222.196.100.5
    igor@ubuntu-server:~$

    Happy coding everyone!

    Share my post if you like it.

  • How to create mock server response and connect to Android Retrofit

    How to create mock server response and connect to Android Retrofit

    Here I want to talk about mock responses for your Retrofit.

    Sometimes we should continue mobile development even backend not ready. We can be never blocked on it if will use mock responses. Sure we need specify JSON response before starting. But we need only JSON format of the backend response to start.

    Let’s see.

    First we need create implementation of Interceptor and this class will contains all logic for server responses.

    Feel free parse requests and create your own if/else cases

    Here is sample FakeInterceptor.java

    package com.hrupin.fakeinterceptorsample.retrofit;
    
    import android.content.Context;
    import android.util.Log;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.List;
    
    import okhttp3.Interceptor;
    import okhttp3.MediaType;
    import okhttp3.Protocol;
    import okhttp3.Request;
    import okhttp3.Response;
    import okhttp3.ResponseBody;
    import okio.Buffer;
    
    /**
     *
     */
    public class FakeInterceptor implements Interceptor {
        private static final String TAG = FakeInterceptor.class.getSimpleName();
        private static final String FILE_EXTENSION = ".json";
        private Context mContext;
    
        private String mContentType = "application/json";
    
        public FakeInterceptor(Context context) {
            mContext = context;
        }
    
        /**
         * Set content type for header
         *
         * @param contentType Content type
         * @return FakeInterceptor
         */
        public FakeInterceptor setContentType(String contentType) {
            mContentType = contentType;
            return this;
        }
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            List<String> listSuggestionFileName = new ArrayList<>();
            String method = chain.request().method().toLowerCase();
    
            Response response = null;
            // Get Request URI.
            final URI uri = chain.request().url().uri();
            Log.d(TAG, "--> Request url: [" + method.toUpperCase() + "]" + uri.toString());
    
            String defaultFileName = getFileName(chain);
    
            if (defaultFileName != null) {
                String fileName = getFilePath(uri, defaultFileName);
                Log.d(TAG, "Read data from file: " + fileName);
                try {
                    InputStream is = mContext.getAssets().open(fileName);
                    BufferedReader r = new BufferedReader(new InputStreamReader(is));
                    StringBuilder responseStringBuilder = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        responseStringBuilder.append(line).append('\n');
                    }
                    Log.d(TAG, "Response: " + responseStringBuilder.toString());
                    Response.Builder builder = new Response.Builder();
                    builder.request(chain.request());
                    builder.protocol(Protocol.HTTP_1_0);
                    builder.addHeader("content-type", mContentType);
    
                    builder.body(ResponseBody.create(MediaType.parse(mContentType), responseStringBuilder.toString().getBytes()));
                    builder.code(200);
                    builder.message(responseStringBuilder.toString());
    
                    response = builder.build();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            } else {
                for (String file : listSuggestionFileName) {
                    Log.e(TAG, "File not exist: " + getFilePath(uri, file));
                }
                response = chain.proceed(chain.request());
            }
    
            Log.d(TAG, "<-- END [" + method.toUpperCase() + "]" + uri.toString());
            return response;
        }
    
        private String getFileName(Chain chain) {
    
            String method = chain.request().method();
            if (method.equals("POST")) {
                String fileName = null;
                String lastSegment = chain.request().url().pathSegments().get(chain.request().url().pathSegments().size() - 1);
    
                if (lastSegment.equals("login")) {
                    fileName = "login";
                } else {
                    fileName = lastSegment;
                }
    
                return fileName + FILE_EXTENSION;
            }
            return "none" + FILE_EXTENSION;
        }
    
        private String getFilePath(URI uri, String fileName) {
            String path;
            if (uri.getPath().lastIndexOf('/') != uri.getPath().length() - 1) {
                path = uri.getPath().substring(0, uri.getPath().lastIndexOf('/') + 1);
            } else {
                path = uri.getPath();
            }
            return uri.getHost() + path + fileName;
        }
    }
    

    The key method is public Response intercept(Chain chain). You can play inside this method and prepare responses for your client side.

    I’ve created sample login form with mock server requests

    OkHttp log

    D/OkHttp: --> POST http://mockapi/login http/1.1
    D/OkHttp: Content-Type: application/json
    D/OkHttp: Content-Length: 47
    D/OkHttp: Accept: application/json
    D/OkHttp: {"email":"test@test.com","password":"password"}
    D/OkHttp: --> END POST (47-byte body)
    D/OkHttp: <-- 200 {
    D/OkHttp:   "id":"uceruc65tfvifbvuyfd67t",
    D/OkHttp:   "name":"John"
    D/OkHttp: }
    D/OkHttp:  http://mockapi/login (1ms)
    D/OkHttp: content-type: application/json
    D/OkHttp: {
    D/OkHttp:   "id":"uceruc65tfvifbvuyfd67t",
    D/OkHttp:   "name":"John"
    D/OkHttp: }
    D/OkHttp: <-- END HTTP (53-byte body)

     

    Download it from github

    Feel free download source code of the sample application from my github

    Nice codding

  • How to configure PHP with Nginx webserver on Mac OS X

    How to configure PHP with Nginx webserver on Mac OS X

    Before starting installation PHP-FPM and configurations you should have Nginx installed and configured. If you don’t have it ready please follow my previous post about installing and configuring Nginx on Mac OS X. Here is the link https://www.hrupin.com/2017/11/how-to-install-nginx-webserver-on-mac-os-x

    So, here we have installed and configured NGinx. Let’s install and configure PHP-FPM. Here is step by step instructions

    • Install php71 using Homebrew
      brew tap homebrew/dupes
      brew tap homebrew/php
      brew search php
      brew install php71 --without-apache --with-fpm
    • Setup automatic launch php after mac start
      mkdir -p ~/Library/LaunchAgents
      cp /usr/local/opt/php71/homebrew.mxcl.php71.plist ~/Library/LaunchAgents/
      launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php71.plist
    • Edit /usr/local/etc/php/7.1/php.ini and replace
      ;cgi.fix_pathinfo=1

      with next string

      cgi.fix_pathinfo=0
    • Edit /usr/local/etc/php/7.1/php-fpm.d/www.conf file and put there your username and group. You need find next lines and edit them like next. Please replace YOUR_USERNAME with your username and YOUR_GROUP with name of your group
      user = YOUR_USERNAME
      group = YOUR_GROUP
    • Next we need edit default virtualhost and add make it look like this
      server {
          listen   80; ## listen for ipv4; this line is default and implied
          listen   [::]:80 default_server ipv6only=on; ## listen for ipv6
      
          server_name  localhost;
          
          root       /var/www/localhost;
      
          index index.php index.html index.htm;
       
          access_log  /usr/local/etc/nginx/logs/default.access.log;
          error_log  /usr/local/etc/nginx/logs/default.error.log;
       
          location ~ \.php$ {
              try_files      $uri = 404;
              fastcgi_pass   127.0.0.1:9000;
              fastcgi_index  index.php;
              fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
              include        fastcgi_params;
          }
      
          error_page  404     /404.html;
          error_page  403     /403.html;
      }
    • Install mcrypt
      sudo brew install php71-mcrypt
    • Prepare test web content. Create file  /var/www/localhost/info.php with next content
      <?php
          phpinfo();
      ?>
    • Save all files and restart PHP
      sudo brew services stop php71
      sudo brew services start php71
    • Restart Nginx
      sudo nginx -s stop
      sudo nginx
    • Check how Nginx works
      curl -IL http://localhost/info.php
    • Output should be like this
      HTTP/1.1 200 OK
      Server: nginx/1.12.1
      Date: Sat, 11 Nov 2017 22:01:37 GMT
      Content-Type: text/html; charset=UTF-8
      Connection: keep-alive
      X-Powered-By: PHP/7.1.11
    • Also you can run http://localhost/info.php in your browser and you should see phpinfo table like this

    Now Nginx able to work with PHP

  • How to install Nginx webserver on Mac OS X

    How to install Nginx webserver on Mac OS X

    Before start you should ensure that you have Command Line Tools installed in your mac. It is part of XCode. You should have it installed and updated.

    • Install Command Line Tools if not exist
      xcode-select --install
    • Install Nginx using Homebrew
      brew tap homebrew nginx 
      brew install nginx
      
    • Test Installation
      ## Start Nginx
      sudo nginx
      
      ## Check if Nginx is running on 8080 port
      curl -IL http://127.0.0.1:8080
    • Output should look like this
      HTTP/1.1 200 OK
      Server: nginx/1.12.1
      Date: Sat, 11 Nov 2017 21:11:39 GMT
      Content-Type: text/html
      Content-Length: 138
      Last-Modified: Sat, 11 Nov 2017 19:49:46 GMT
      Connection: keep-alive
      ETag: "5a07545a-8a"
      Accept-Ranges: bytes
    • Also you can open http://127.0.0.1:8080 in your browser. You should get the next page 

    Nginx installed successful.

    I prefer to make configurations for virtual hosts right after webserver installation. You can do the same using following instructions

    • Prepare dirs before making configuration
      mkdir -p /usr/local/etc/nginx/logs
      mkdir -p /usr/local/etc/nginx/sites-available
      mkdir -p /usr/local/etc/nginx/sites-enabled
      sudo mkdir -p /var/www
      sudo chown :staff /var/www
      sudo chmod 775 /var/www
    • Prepare default content for webpages. Create /var/www/localhost/index.html file with following content
      <!DOCTYPE html>
      <html>
      	<head>
      		<title>Localhost</title>
      	</head>
      	<body>
      		<h1>It Works!</h1>
      		<p>Welcome to Nginx</p>
      	</body>
      </html>
    • Edit Nginx config file /usr/local/etc/nginx/nginx.conf and make it look like this
      worker_processes  1;
       
      error_log  /usr/local/etc/nginx/logs/error.log debug;
       
      events {
          worker_connections  1024;
      }
       
      http {
          include             mime.types;
          default_type        application/octet-stream;
       
          log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';
       
          access_log  /usr/local/etc/nginx/logs/access.log  main;
       
          sendfile            on;
       
          keepalive_timeout   65;
       
          index index.html index.php;
       
          include /usr/local/etc/nginx/sites-enabled/*; 
      }
    • Create /usr/local/etc/nginx/sites-available/default file with following content
      server {
          listen       80;
          server_name  localhost;
          root       /var/www/localhost/;
       
          access_log /usr/local/etc/nginx/logs/default.access.log;
          error_log /usr/local/etc/nginx/logs/default.error.log;
      
          error_page  404     /404.html;
          error_page  403     /403.html;
      }
    • Make symbolic link to sites-avalable/default into sites-enabled
      sudo ln -s /usr/local/etc/nginx/sites-available/default /usr/local/etc/nginx/sites-enabled/default
    • Save files and restart Nginx
      sudo nginx -s stop
      sudo nginx
    • Check how Nginx works
      curl -IL http://localhost
    • Output should look like this
      HTTP/1.1 200 OK
      Server: nginx/1.12.1
      Date: Sat, 11 Nov 2017 21:29:44 GMT
      Content-Type: text/html
      Content-Length: 138
      Last-Modified: Sat, 11 Nov 2017 19:49:46 GMT
      Connection: keep-alive
      ETag: "5a07545a-8a"
      Accept-Ranges: bytes
    • Also you can open your browser with http://localhost. You should see neext

    Nginx installed. Next  post will be about Nginx and PHP configurations