One place for hosting & domains

      Cómo instalar WordPress con LEMP en Ubuntu 18.04


      Introducción

      WordPress es el sistema de gestión de contenido (CMS) más popular de Internet. Le permite configurar de forma sencilla blogs y sitios web flexibles sobre un backend de MySQL con procesamiento PHP. WordPress ha recibido una increíble acogida y es una excelente opción para dejar listo un sitio web de forma rápida. Después de la configuración, casi toda la administración puede hacerse a través del cliente web.

      En esta guía, nos centraremos en crear una instancia de WordPress configurada en una pila LEMP (Linux, Nginx, MySQL y PHP) en un servidor de Ubuntu 18.04.

      Requisitos previos

      Para completar este tutorial, necesitará acceso a un servidor de Ubuntu 18.04.

      Deberá realizar las siguientes tareas para poder comenzar con esta guía:

      • Cree un usuario sudo en su servidor: completaremos los pasos de esta guía usando un usuario no root con privilegios sudo. Puede crear un usuario con privilegios sudo siguiendo nuestra guía de configuración inicial para servidores de Ubuntu 18.04.
      • Instale una pila LEMP: WordPress necesitará un servidor web, una base de datos y PHP para que funcione correctamente. La configuración de una pila LEMP (Linux, Nginx, MySQL y PHP) cumple con todos estos requisitos. Siga esta guía para instalar y configurar este software.
      • Proteja su sitio con SSL: WordPress proporciona contenido dinámico y se ocupa de la autenticación y la autorización del usuario. TLS/SSL es la tecnología que le permite cifrar el tráfico de su sitio para que su conexión sea segura. La forma en que configure SSL dependerá de que disponga o no de un nombre de dominio para su sitio.
        • *Si tiene un nombre de dominio, la alternativa *más sencilla para proteger su sitio es Let’s Encrypt, que proporciona certificados de confianza gratuitos. Para la configuración, siga nuestra guía de Let’s Encrypt para Nginx.
        • Si no cuenta con un dominio y solo utiliza esta configuración para pruebas o cuestiones personales, puede emplear en su lugar un certificado autofirmado. Le proporciona el mismo tipo de cifrado, aunque sin la validación del dominio. Para la configuración, siga nuestra guía de SSL autofirmados para Nginx.

      Cuando complete los pasos de configuración, inicie sesión en su servidor como usuario sudo y continúe.

      Paso 1: Crear una base de datos y un usuario de MySQL para WordPress

      El primer paso que daremos es preparatorio. WordPress utiliza MySQL para administrar y almacenar información sobre el sitio y el usuario. Ya instalamos MySQL, pero debemos crear una base de datos y un usuario para que WordPress los utilice.

      Para comenzar, inicie sesión en la cuenta root (administrativa) de MySQL. Si MySQL está configurado para usar el complemento de autenticación auth_socket (el predeterminado), puede iniciar sesión en la cuenta administrativa de MySQL usando sudo:

      Si cambió el método de autenticación para usar una contraseña para la cuenta root de MySQL, utilice el siguiente formato:

      Se le solicitará la contraseña que estableció para la cuenta root de MySQL.

      Primero, podemos crear una base de datos separada que WordPress pueda controlar. Puede darle el nombre que desee, pero en esta guía usaremos wordpress por cuestiones de simplicidad. Puede crear la base de datos para WordPress escribiendo lo siguiente:

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Nota: Cada instrucción de MySQL debe terminar en punto y coma (;). Asegúrese de que esto no falte si experimenta problemas.

      A continuación, crearemos una cuenta de usuario separada de MySQL que usaremos exclusivamente para realizar operaciones en nuestra nueva base de datos. Desde el punto de vista de la administración y la seguridad, crear bases de datos y cuentas de una función es una idea recomendable. En esta guía, usaremos el nombre wordpressuser. Puede cambiarlo si lo desea.

      Crearemos esta cuenta, estableceremos una contraseña y concederemos acceso a la base de datos que creamos. Podemos hacerlo escribiendo el comando que se muestra a continuación. Recuerde elegir una contraseña segura para el usuario de su base de datos:

      • GRANT ALL ON wordpress.* TO 'wordpressuser'@'localhost' IDENTIFIED BY 'password';

      Ahora tiene una base de datos y una cuenta de usuario, creadas específicamente para WordPress. Debemos eliminar los privilegios de modo que la instancia actual de MySQL registre los cambios recientes que realizamos:

      Cierre MySQL escribiendo lo siguiente:

      La sesión de MySQL terminará y volverá al shell normal de Linux.

      Paso 2: Instalar extensiones de PHP adicionales

      Cuando configuramos nuestra pila LEMP, solo necesitamos un conjunto de extensiones muy reducido para que PHP se comunicara con MySQL. WordPress y muchos de sus complementos aprovechan las extensiones de PHP adicionales.

      Podemos descargar e instalar algunas de las extensiones de PHP más populares para usarlas con WordPress escribiendo lo siguiente:

      • sudo apt update
      • sudo apt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip

      Nota: Cada complemento de WordPress tiene su propio conjunto de requisitos. Para algunos, posiblemente sea necesario instalar paquetes de PHP adicionales. Compruebe la documentación de sus complementos para ver sus requisitos de PHP. Si están disponibles, pueden instalarse con apt como ya se ha mostrado.

      Cuando termine de instalar las extensiones, reinicie el proceso PHP-FPM de modo que el procesador PHP en funcionamiento pueda aprovechar las características recién instaladas:

      • sudo systemctl restart php7.2-fpm

      Ahora tenemos instaladas todas las extensiones de PHP necesarias en el servidor.

      Paso 3: Configurar Nginx

      A continuación, realizaremos algunos ajustes de menor importancia en nuestros archivos de bloque del servidor de Nginx. Conforme a los tutoriales de requisitos previos, debe tener un archivo de configuración para su sitio en el directorio /etc/nginx/sites-available/ configurado para responder al nombre de dominio o a la dirección IP de su servidor y protegido por un certificado TLS/SSL. Como ejemplo, utilizaremos /etc/apache2/sites-available/wordpress, pero debe sustituir la ruta a su archivo de configuración cuando proceda.

      Además, emplearemos /var/www/wordpress como el directorio root de nuestra instalación de WordPress. Debería usar el root web especificada en su propia configuración.

      Nota: Es posible que utilice la configuración predeterminada /etc/nginx/sites-available/default (con /var/www/html como su root web). Se puede usar si solo piensa alojar un sitio web en este servidor. Si no piensa hacerlo, resulta mejor dividir la configuración necesaria en fragmentos lógicos, de un archivo por sitio.

      Abra el archivo de bloque del servidor de su sitio con privilegios sudo para comenzar:

      • sudo nano /etc/nginx/sites-available/wordpress

      Dentro del bloque principal server, debemos añadir algunos bloques location.

      Comience creando bloques location con coincidencia exacta para solicitudes a /favicon.ico y /robots.txt, para los que no queremos solicitudes de registro.

      Usaremos una ubicación de expresión regular para que coincida con cualquier solicitud de archivos estáticos. Una vez más, desactivaremos el registro para estas solicitudes y las marcaremos como caché, ya que suelen ser recursos exigentes. Puede ajustar esta lista de archivos estáticos para que contenga cualquier otra extensión de archivo que pueda usar su sitio:

      /etc/nginx/sites-available/wordpress

      server {
          . . .
      
          location = /favicon.ico { log_not_found off; access_log off; }
          location = /robots.txt { log_not_found off; access_log off; allow all; }
          location ~* .(css|gif|ico|jpeg|jpg|js|png)$ {
              expires max;
              log_not_found off;
          }
          . . .
      }
      

      Dentro del bloque location/ existente, debemos ajustar la lista de try_files de modo que en vez de mostrar un error 404 como la opción predeterminada, el control pase al archivo index.php con los argumentos de solicitud.

      Debería tener un aspecto parecido al siguiente:

      /etc/nginx/sites-available/wordpress

      server {
          . . .
          location / {
              #try_files $uri $uri/ =404;
              try_files $uri $uri/ /index.php$is_args$args;
          }
          . . .
      }
      

      Cuando termine, guarde y cierre el archivo.

      Ahora podemos verificar que en nuestra configuración no haya errores de sintaxis escribiendo lo siguiente:

      Si no se notificaron errores, vuelva a cargar Nginx escribiendo lo siguiente:

      • sudo systemctl reload nginx

      A continuación, descargaremos y configuraremos el propio WordPress.

      Paso 4: Descargar WordPress

      Ahora que el software de nuestro servidor está configurado, podemos descargar y configurar WordPress. Preferentemente por motivos de seguridad, siempre se recomienda obtener la versión más reciente de WordPress del sitio del producto.

      Posiciónese en un directorio editable y luego descargue la versión comprimida escribiendo lo siguiente:

      • cd /tmp
      • curl -LO https://wordpress.org/latest.tar.gz

      Extraiga el archivo comprimido para crear la estructura de directorios de WordPress:

      Moveremos estos archivos a nuestro root de documentos por ahora. Antes de hacerlo, podemos copiar el archivo de configuración de muestra al nombre del archivo que WordPress lee realmente:

      • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

      Ahora podemos copiar todo el contenido del directorio en nuestro root de documentos. Usaremos el indicador -a para comprobar que se conserven nuestros permisos. Utilizaremos un punto al final de nuestro directorio de origen para indicar que todo lo que esté dentro del directorio debe copiarse, incluidos los archivos ocultos:

      • sudo cp -a /tmp/wordpress/. /var/www/wordpress

      Ahora que nuestros archivos están preparados, les asignaremos propiedad al usuario y al grupo www-data. Este es el usuario cuyo funcionamiento Nginx simula y este último deberá poder leer y escribir archivos de WordPress para representar el sitio web y realizar actualizaciones automáticas.

      • sudo chown -R www-data:www-data /var/www/wordpress

      Ahora nuestros archivos están en el root de documentos de nuestro servidor y su propiedad es correcta, pero aún debemos completar otras configuraciones.

      Paso 5: Aplicar ajustes al archivo de configuración de WordPress

      A continuación, debemos realizar algunos cambios en el archivo de configuración principal de WordPress.

      Cuando abramos el archivo, nuestra primera tarea será ajustar algunas claves secretas para proporcionar seguridad a nuestra instalación. WordPress proporciona un generador seguro para estos valores, de modo que no tenga que crear valores buenos por su cuenta. Solo se utilizan de forma interna, de modo que tener valores complejos y seguros aquí no afectará de manera negativa la utilidad.

      Para obtener valores seguros del generador de claves secretas de WordPress, escriba lo siguiente:

      • curl -s https://api.wordpress.org/secret-key/1.1/salt/

      Obtendrá valores únicos como estos:

      Advertencia: Debe solicitar valores únicos en cada ocasión. NO copie los valores que se muestran a continuación.

      Output

      define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

      Son líneas de configuración que podemos pegar directamente en nuestro archivo de configuración para establecer claves seguras. Copie el resultado que obtuvo ahora.

      A continuación, abra el archivo de configuración de WordPress:

      • sudo nano /var/www/wordpress/wp-config.php

      Busque la sección que contiene los valores ficticios para esos ajustes. Se parecerá a esto:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'put your unique phrase here');
      define('SECURE_AUTH_KEY',  'put your unique phrase here');
      define('LOGGED_IN_KEY',    'put your unique phrase here');
      define('NONCE_KEY',        'put your unique phrase here');
      define('AUTH_SALT',        'put your unique phrase here');
      define('SECURE_AUTH_SALT', 'put your unique phrase here');
      define('LOGGED_IN_SALT',   'put your unique phrase here');
      define('NONCE_SALT',       'put your unique phrase here');
      
      . . .
      

      Elimine esas líneas y pegue los valores que copió de la línea de comandos:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
      define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');
      
      . . .
      

      A continuación, debemos modificar algunos de los ajustes de conexión de la base de datos al inicio del archivo. Debe ajustar el nombre de la base de datos, su usuario y la contraseña asociada que configuramos dentro de MySQL.

      El otro cambio que debemos realizar es configurar el método que debe emplear WordPress para escribir el sistema de archivos. Debido a que hemos dado permiso al servidor web para escribir donde debe hacerlo, podemos fijar de forma explícita el método del sistema de archivos en “direct”. Si no lo configuramos con nuestros ajustes actuales, haría que WordPress solicitase las credenciales de FTP cuando realicemos algunas acciones. Este ajuste se puede agregar debajo de los ajustes de conexión de la base de datos o en cualquier otra parte del archivo:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('DB_NAME', 'wordpress');
      
      /** MySQL database username */
      define('DB_USER', 'wordpressuser');
      
      /** MySQL database password */
      define('DB_PASSWORD', 'password');
      
      . . .
      
      define('FS_METHOD', 'direct');
      

      Guarde y cierre el archivo cuando termine.

      Paso 6: Completar la instalación a través de la interfaz web

      Ahora que la configuración del servidor está completa, podemos finalizar la instalación a través de la interfaz web.

      En su navegador web, diríjase al nombre de dominio o a la dirección IP pública de su servidor:

      http://server_domain_or_IP
      

      Seleccione el idioma que desee utilizar:

      Selección de idioma de WordPress

      A continuación, accederá a la página principal de configuración.

      Seleccione un nombre para su sitio de WordPress y elija un nombre de usuario (por motivos de seguridad, se recomienda no elegir opciones como “admin”). De forma automática, se generará una contraseña segura. Guárdela o seleccione una contraseña segura alternativa.

      Introduzca su dirección de correo electrónico y defina si quiere que los motores de búsqueda no indexen su sitio:

      Instalación de la configuración de WordPress

      Cuando haga clic para seguir, accederá a una página que le solicitará registrarse:

      Solicitud de inicio de sesión de WordPress

      Tras iniciar sesión, accederá al panel de administración de WordPress:

      Solicitud de inicio de sesión de WordPress

      Conclusión

      Con esto, WordPress deberá quedar instalado y listo para utilizarse. Algunos pasos posteriores comunes son elegir el ajuste de los permalinks para sus publicaciones (puede encontrarse en Settings > Permalinks) o seleccionar un nuevo tema (en Appearance > Themes). Si es la primera vez que utiliza WordPress, explore la interfaz un poco para conocer su nuevo CMS.



      Source link

      How to Install and Configure Laravel with LEMP on Ubuntu 18.04


      Introduction

      Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. With a complete ecosystem leveraging its built-in features, Laravel’s popularity has grown rapidly in the past few years, with many developers adopting it as their framework of choice for a streamlined development process.

      In this guide, you’ll install and configure a new Laravel application on an Ubuntu 18.04 server, using Composer to download and manage the framework dependencies. When you’re finished, you’ll have a functional Laravel demo application pulling content from a MySQL database.

      Prerequisites

      In order to complete this guide, you will first need to perform the following tasks on your Ubuntu 18.04 server:

      Step 1 — Installing Required PHP modules

      Before you can install Laravel, you need to install a few PHP modules that are required by the framework. We’ll use apt to install the php-mbstring, php-xml and php-bcmath PHP modules. These PHP extensions provide extra support for dealing with character encoding, XML and precision mathematics.

      If this is the first time using apt in this session, you should first run the update command to update the package manager cache:

      Now you can install the required packages with:

      • sudo apt install php-mbstring php-xml php-bcmath

      Your system is now ready to execute Laravel's installation via Composer, but before doing so, you'll need a database for your application.

      Step 2 — Creating a Database for the Application

      To demonstrate Laravel's basic installation and usage, we'll create a sample travel list application to show a list of places a user would like to travel to, and a list of places that they already visited. This can be stored in a simple places table with a field for locations that we'll call name and another field to mark them as visited or not visited, which we'll call visited. Additionally, we'll include an id field to uniquely identify each entry.

      To connect to the database from the Laravel application, we'll create a dedicated MySQL user, and grant this user full privileges over the travel_list database.

      To get started, log in to the MySQL console as the root database user with:

      To create a new database, run the following command from your MySQL console:

      • CREATE DATABASE travel_list;

      Now you can create a new user and grant them full privileges on the custom database you've just created. In this example, we're creating a user named travel_user with the password password, though you should change this to a secure password of your choosing:

      • GRANT ALL ON travel_list.* TO 'travel_user'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

      This will give the travel_user user full privileges over the travel_list database, while preventing this user from creating or modifying other databases on your server.

      Following this, exit the MySQL shell:

      You can now test if the new user has the proper permissions by logging in to the MySQL console again, this time using the custom user credentials:

      Note the -p flag in this command, which will prompt you for the password used when creating the travel_user user. After logging in to the MySQL console, confirm that you have access to the travel_list database:

      This will give you the following output:

      Output

      +--------------------+ | Database | +--------------------+ | information_schema | | travel_list | +--------------------+ 2 rows in set (0.01 sec)

      Next, create a table named places in the travel_list database. From the MySQL console, run the following statement:

      • CREATE TABLE travel_list.places (
      • id INT AUTO_INCREMENT,
      • name VARCHAR(255),
      • visited BOOLEAN,
      • PRIMARY KEY(id)
      • );

      Now, populate the places table with some sample data:

      • INSERT INTO travel_list.places (name, visited)
      • VALUES ("Tokyo", false),
      • ("Budapest", true),
      • ("Nairobi", false),
      • ("Berlin", true),
      • ("Lisbon", true),
      • ("Denver", false),
      • ("Moscow", false),
      • ("Olso", false),
      • ("Rio", true),
      • ("Cincinati", false),

      To confirm that the data was successfully saved to your table, run:

      • SELECT * FROM travel_list.places;

      You will see output similar to this:

      Output

      +----+-----------+---------+ | id | name | visited | +----+-----------+---------+ | 1 | Tokyo | 0 | | 2 | Budapest | 1 | | 3 | Nairobi | 0 | | 4 | Berlin | 1 | | 5 | Lisbon | 1 | | 6 | Denver | 0 | | 7 | Moscow | 0 | | 8 | Oslo | 0 | | 9 | Rio | 1 | | 10 | Cincinati | 0 | +----+-----------+---------+ 10 rows in set (0.00 sec)

      After confirming that you have valid data in your test table, you can exit the MySQL console:

      You're now ready to create the application and configure it to connect to the new database.

      Step 3 — Creating a New Laravel Application

      You will now create a new Laravel application using the composer create-project command. This Composer command is typically used to bootstrap new applications based on existing frameworks and content management systems.

      Throughout this guide, we'll use travel_list as an example application, but you are free to change this to something else. The travel_list application will display a list of locations pulled from a local MySQL server, intended to demonstrate Laravel's basic configuration and confirm that you're able to connect to the database.

      First, go to your user's home directory:

      The following command will create a new travel_list directory containing a barebones Laravel application based on default settings:

      • composer create-project --prefer-dist laravel/laravel travel_list

      You will see output similar to this:

      Output

      Installing laravel/laravel (v5.8.17) - Installing laravel/laravel (v5.8.17): Downloading (100%) Created project in travel_list > @php -r "file_exists('.env') || copy('.env.example', '.env');" Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 80 installs, 0 updates, 0 removals - Installing symfony/polyfill-ctype (v1.11.0): Downloading (100%) - Installing phpoption/phpoption (1.5.0): Downloading (100%) - Installing vlucas/phpdotenv (v3.4.0): Downloading (100%) - Installing symfony/css-selector (v4.3.2): Downloading (100%) ...

      When the installation is finished, access the application's directory and run Laravel's artisan command to verify that all components were successfully installed:

      • cd travel_list
      • php artisan

      You'll see output similar to this:

      Output

      Laravel Framework 5.8.29 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --env[=ENV] The environment the command should run under -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug (...)

      This output confirms that the application files are in place, and the Laravel command-line tools are working as expected. However, we still need to configure the application to set up the database and a few other details.

      Step 4 — Configuring Laravel

      The Laravel configuration files are located in a directory called config, inside the application's root directory. Additionally, when you install Laravel with Composer, it creates an environment file. This file contains settings that are specific to the current environment the application is running, and will take precedence over the values set in regular configuration files located at the config directory. Each installation on a new environment requires a tailored environment file to define things such as database connection settings, debug options, application URL, among other items that may vary depending on which environment the application is running.

      Warning: The environment configuration file contains sensitive information about your server, including database credentials and security keys. For that reason, you should never share this file publicly.

      We'll now edit the .env file to customize the configuration options for the current application environment.

      Open the .env file using your command line editor of choice. Here we'll use nano:

      Even though there are many configuration variables in this file, you don't need to set up all of them now. The following list contains an overview of the variables that require immediate attention:

      • APP_NAME: Application name, used for notifications and messages.
      • APP_ENV: Current application environment.
      • APP_KEY: Used for generating salts and hashes, this unique key is automatically created when installing Laravel via Composer, so you don't need to change it.
      • APP_DEBUG: Whether or not to show debug information at client side.
      • APP_URL: Base URL for the application, used for generating application links.
      • DB_DATABASE: Database name.
      • DB_USERNAME: Username to connect to the database.
      • DB_PASSWORD: Password to connect to the database.

      By default, these values are configured for a local development environment that uses Homestead, a prepackaged Vagrant box provided by Laravel. We'll change these values to reflect the current environment settings of our example application.

      In case you are installing Laravel in a development or testing environment, you can leave the APP_DEBUG option enabled, as this will give you important debug information while testing the application from a browser. The APP_ENV variable should be set to development or testing in this case.

      In case you are installing Laravel in a production environment, you should disable the APP_DEBUG option, because it shows to the final user sensitive information about your application. The APP_ENV in this case should be set to production.

      The following .env file sets up our example application for development:

      Note: The APP_KEY variable contains a unique key that was auto generated when you installed Laravel via Composer. You don't need to change this value. If you want to generate a new secure key, you can use the php artisan key:generate command.

      /var/www/travel_list/.env

      APP_NAME=TravelList
      APP_ENV=development
      APP_KEY=APPLICATION_UNIQUE_KEY_DONT_COPY
      APP_DEBUG=true
      APP_URL=http://domain_or_IP
      
      LOG_CHANNEL=stack
      
      DB_CONNECTION=mysql
      DB_HOST=127.0.0.1
      DB_PORT=3306
      DB_DATABASE=travel_list
      DB_USERNAME=travel_user
      DB_PASSWORD=password
      
      ...
      

      Adjust your variables accordingly. When you are done editing, save and close the file to keep your changes. If you're using nano, you can do that with CTRL+X, then Y and Enter to confirm.

      Your Laravel application is now set up, but we still need to configure the web server in order to be able to access it from a browser. In the next step, we'll configure Nginx to serve your Laravel application.

      Step 5 — Setting Up Nginx

      We have installed Laravel on a local folder of your remote user's home directory, and while this works well for local development environments, it's not a recommended practice for web servers that are open to the public internet. We'll move the application folder to /var/www, which is the usual location for web applications running on Nginx.

      First, use the mv command to move the application folder with all its contents to /var/www/travel_list:

      • sudo mv ~/travel_list /var/www/travel_list

      Now we need to give the web server user write access to the storage and cache folders, where Laravel stores application-generated files:

      • sudo chown -R www-data.www-data /var/www/travel_list/storage
      • sudo chown -R www-data.www-data /var/www/travel_list/bootstrap/cache

      The application files are now in order, but we still need to configure Nginx to serve the content. To do this, we'll create a new virtual host configuration file at /etc/nginx/sites-available:

      • sudo nano /etc/nginx/sites-available/travel_list

      The following configuration file contains the recommended settings for Laravel applications on Nginx:

      /etc/nginx/sites-available/travel_list

      server {
          listen 80;
          server_name server_domain_or_IP;
          root /var/www/travel_list/public;
      
          add_header X-Frame-Options "SAMEORIGIN";
          add_header X-XSS-Protection "1; mode=block";
          add_header X-Content-Type-Options "nosniff";
      
          index index.html index.htm index.php;
      
          charset utf-8;
      
          location / {
              try_files $uri $uri/ /index.php?$query_string;
          }
      
          location = /favicon.ico { access_log off; log_not_found off; }
          location = /robots.txt  { access_log off; log_not_found off; }
      
          error_page 404 /index.php;
      
          location ~ .php$ {
              fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
              fastcgi_index index.php;
              fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
              include fastcgi_params;
          }
      
          location ~ /.(?!well-known).* {
              deny all;
          }
      }
      

      Copy this content to your /etc/nginx/sites-available/travel_list file and, if necessary, adjust the highlighted values to align with your own configuration. Save and close the file when you're done editing.

      To activate the new virtual host configuration file, create a symbolic link to travel_list in sites-enabled:

      • sudo ln -s /etc/nginx/sites-available/travel_list /etc/nginx/sites-enabled/

      Note: If you have another virtual host file that was previously configured for the same server_name used in the travel_list virtual host, you might need to deactivate the old configuration by removing the corresponding symbolic link inside /etc/nginx/sites-enabled/.

      To confirm that the configuration doesn't contain any syntax errors, you can use:

      You should see output like this:

      Output

      • nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
      • nginx: configuration file /etc/nginx/nginx.conf test is successful

      To apply the changes, reload Nginx with:

      • sudo systemctl reload nginx

      Now go to your browser and access the application using the server's domain name or IP address, as defined by the server_name directive in your configuration file:

      http://server_domain_or_IP
      

      You will see a page like this:

      Laravel splash page

      That confirms your Nginx server is properly configured to serve Laravel. From this point, you can start building up your application on top of the skeleton provided by the default installation.

      In the next step, we'll modify the application's main route to query for data in the database using Laravel's DB facade.

      Step 6 — Customizing the Main Page

      Assuming you've followed all the steps in this guide so far, you should have a working Laravel application and a database table named places containing some sample data.

      We'll now edit the main application route to query for the database and return the contents to the application's view.

      Open the main route file, routes/web.php:

      This file comes by default with the following content:

      routes/web.php

      <?php
      
      /*
      |--------------------------------------------------------------------------
      | Web Routes
      |--------------------------------------------------------------------------
      |
      | Here is where you can register web routes for your application. These
      | routes are loaded by the RouteServiceProvider within a group which
      | contains the "web" middleware group. Now create something great!
      |
      */
      
      Route::get('/', function () {
          return view('welcome');
      });
      
      

      Routes are defined within this file using the static method Route::get, which receives a path and a callback function as arguments.

      The following code replaces the main route callback function. It makes 2 queries to the database using the visited flag to filter results. It returns the results to a view named travel_list, which we're going to create next. Copy this content to your routes/web.php file, replacing the code that is already there:

      routes/web.php

      <?php
      
      use IlluminateSupportFacadesDB;
      
      Route::get('/', function () {
        $visited = DB::select('select * from places where visited = ?', [1]); 
        $togo = DB::select('select * from places where visited = ?', [0]);
      
        return view('travel_list', ['visited' => $visited, 'togo' => $togo ] );
      });
      

      Save and close the file when you're done editing. We'll now create the view that will render the database results to the user. Create a new view file inside resources/views:

      • nano resources/views/travel_list.blade.php

      The following template creates two lists of places based on the variables visited and togo. Copy this content to your new view file:

      resources/views/travel_list/blade.php

      <html>
      <head>
          <title>Travel List</title>
      </head>
      
      <body>
          <h1>My Travel Bucket List</h1>
          <h2>Places I'd Like to Visit</h2>
          <ul>
            @foreach ($togo as $newplace)
              <li>{{ $newplace->name }}</li>
            @endforeach
          </ul>
      
          <h2>Places I've Already Been To</h2>
          <ul>
                @foreach ($visited as $place)
                      <li>{{ $place->name }}</li>
                @endforeach
          </ul>
      </body>
      </html>
      

      Save and close the file when you're done. Now go to your browser and reload the application. You'll see a page like this:

      Demo Laravel Application

      You have now a functional Laravel application pulling contents from a MySQL database.

      Conclusion

      In this tutorial, you've set up a new Laravel application on top of a LEMP stack (Linux, Nginx, MySQL and PHP), running on an Ubuntu 18.04 server. You've also customized your default route to query for database content and exhibit the results in a custom view.

      From here, you can create new routes and views for any additional pages your application needs. Check the official Laravel documentation for more information on routes, views, and database support. If you're deploying to production, you should also check the optimization section for a few different ways in which you can improve your application's performance.

      For improved security, you should consider installing an TLS/SSL certificate for your server, allowing it to serve content over HTTPS. To this end, you can follow our guide on how to secure your Nginx installation with Let's Encrypt on Ubuntu 18.04.



      Source link

      How To Install WordPress with LEMP (Nginx, MariaDB and PHP) on Debian 10


      Introduction

      WordPress is the most popular CMS (content management system) on the internet. It allows you to easily set up flexible blogs and websites on top of a MySQL-based backend with PHP processing. WordPress has seen incredible adoption and is a great choice for getting a website up and running quickly. After setup, almost all administration can be done through the web frontend.

      In this guide, we’ll focus on getting a WordPress instance set up on a LEMP stack (Linux, Nginx, MariaDB, and PHP) on a Debian 10 server.

      Prerequisites

      In order to complete this tutorial, you will need access to a Debian 10 server.

      You will need to perform the following tasks before you can start this guide:

      • Create a sudo user on your server: We will be completing the steps in this guide using a non-root user with sudo privileges. You can create a user with sudo privileges by following our Debian 10 initial server setup guide.
      • Install a LEMP stack: WordPress will need a web server, a database, and PHP in order to correctly function. Setting up a LEMP stack (Linux, Nginx, MariaDB, and PHP) fulfills all of these requirements. Follow this guide to install and configure this software.
      • Secure your site with SSL: WordPress serves dynamic content and handles user authentication and authorization. TLS/SSL is the technology that allows you to encrypt the traffic from your site so that your connection is secure. This tutorial will assume that you have a domain name for your blog. You can use Let’s Encrypt to get a free SSL certificate for your domain. Follow our Let’s Encrypt guide for Nginx to set this up.

      When you are finished with the setup steps, log into your server as your sudo user and continue below.

      Step 1 — Creating a Database and User for WordPress

      WordPress needs a MySQL-based database to store and manage site and user information. Our setup uses MariaDB, a community fork of the original MySQL project by Oracle. MariaDB is currently the default MySQL-compatible database server available on debian-based package manager repositories.

      To get started, log into the MariaDB root (administrative) account. If MariaDB is configured to use the auth_socket authentication plugin, which is the default, you can log into the MariaDB administrative account using sudo:

      If you changed the authentication method to use a password for the MariaDB root account, use the following format instead:

      You will be prompted for the password you set for the MariaDB root account.

      First, we can create a separate database that WordPress can control. You can name this whatever you would like, but we will be using wordpress in this guide to keep it simple. You can create the database for WordPress by typing:

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Next, we are going to create a separate MariaDB user account that we will use exclusively to operate on our new database. Creating one-function databases and accounts is a good idea from a management and security standpoint. We will use the name wordpress_user in this guide. Feel free to change this if you'd like.

      The following command will create this account, set a password, and grant access to the database we created. Remember to choose a strong password for your database user:

      • GRANT ALL ON wordpress.* TO 'wordpress_user'@'localhost' IDENTIFIED BY 'password';

      You now have a database and a user account, each made specifically for WordPress. We need to flush the privileges so that the current instance of the database server knows about the recent changes we've made:

      Exit out of MariaDB by typing:

      The MariaDB session will exit, returning you to the regular Linux shell.

      Step 2 — Installing Additional PHP Extensions

      When setting up our LEMP stack, we only required a very minimal set of extensions in order to get PHP to communicate with MariaDB. WordPress and many of its plugins leverage additional PHP extensions.

      We can download and install some of the most popular PHP extensions for use with WordPress by typing:

      • sudo apt update
      • sudo apt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip

      Note: Each WordPress plugin has its own set of requirements. Some may require additional PHP packages to be installed. Check your plugin documentation to discover its PHP requirements.

      When you are finished installing the extensions, restart the PHP-FPM process so that the running PHP processor can leverage the newly installed features:

      • sudo systemctl restart php7.3-fpm.service

      We now have all of the necessary PHP extensions installed on the server.

      Step 3 — Configuring Nginx

      Next, we will be making a few minor adjustments to our Nginx server block files. Based on the prerequisite tutorials, you should have a configuration file for your site in the /etc/nginx/sites-available/ directory configured to respond to your server's domain name and protected by a TLS/SSL certificate. We'll use /etc/nginx/sites-available/your_domain as an example here, but you should substitute the path to your configuration file where appropriate.

      Additionally, we will use /var/www/your_domain as the root directory of our WordPress install. You should use the web root specified in your own configuration.

      Note: It's possible you are using the /etc/nginx/sites-available/default default configuration (with /var/www/html as your web root). This is fine to use if you're only going to host one website on this server. If not, it's best to split the necessary configuration into logical chunks, one file per site.

      Open your site's Nginx configuration file with sudo privileges to begin:

      • sudo nano /etc/nginx/sites-available/your_domain

      We need to add a few location directives within our main server block. After adding SSL certificates your config may have two server blocks. If so, find the one that contains root /var/www/your_domain and your other location directives and implement your changes there.

      Start by creating exact-matching location blocks for requests to /favicon.ico and /robots.txt, both of which we do not want to log requests for.

      We will use a regular expression location to match any requests for static files. We will again turn off the logging for these requests and will mark them as highly cacheable since these are typically expensive resources to serve. You can adjust this static files list to contain any other file extensions your site may use:

      /etc/nginx/sites-available/your_domain

      server {
          . . .
      
          location = /favicon.ico { log_not_found off; access_log off; }
          location = /robots.txt { log_not_found off; access_log off; allow all; }
          location ~* .(css|gif|ico|jpeg|jpg|js|png)$ {
              expires max;
              log_not_found off;
          }
          . . .
      }
      

      Inside of the existing location / block, we need to adjust the try_files list so that instead of returning a 404 error as the default option, control is passed to the index.php file with the request arguments.

      This should look something like this:

      /etc/nginx/sites-available/wordpress

      server {
          . . .
          location / {
              #try_files $uri $uri/ =404;
              try_files $uri $uri/ /index.php$is_args$args;
          }
          . . .
      }
      

      When you are finished, save and close the file.

      Now, we can check our configuration for syntax errors by typing:

      If no errors were reported, reload Nginx by typing:

      • sudo systemctl reload nginx

      Next, we will download and set up WordPress itself.

      Step 4 — Downloading WordPress

      Now that our server software is configured, we can download and set up WordPress. For security reasons in particular, it is always recommended to get the latest version of WordPress from their site.

      Change into a writable directory and then download the compressed release by typing:

      • cd /tmp
      • curl -LO https://wordpress.org/latest.tar.gz

      Extract the compressed file to create the WordPress directory structure:

      We will be moving these files into our document root momentarily. Before we do that, we can copy over the sample configuration file to the filename that WordPress actually reads:

      • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

      Now, we can copy the entire contents of the directory into our document root. We are using the -a flag to make sure our permissions are maintained. We are using a dot at the end of our source directory to indicate that everything within the directory should be copied, including any hidden files:

      • sudo cp -a /tmp/wordpress/. /var/www/your_domain

      Now that our files are in place, we'll assign ownership them to the www-data user and group. This is the user and group that Nginx runs as, and Nginx will need to be able to read and write WordPress files in order to serve the website and perform automatic updates.

      • sudo chown -R www-data:www-data /var/www/your_domain

      Our files are now in our server's document root and have the correct ownership, but we still need to complete some more configuration.

      Step 5 — Setting up the WordPress Configuration File

      Next, we need to make a few changes to the main WordPress configuration file.

      When we open the file, our first order of business will be to adjust the secret keys to provide some security for our installation. WordPress provides a secure generator for these values so that you do not have to try to come up with good values on your own. These are only used internally, so it won't hurt usability to have complex, secure values here.

      To grab secure values from the WordPress secret key generator, type:

      • curl -s https://api.wordpress.org/secret-key/1.1/salt/

      You will get back unique values that look something like this:

      Warning: It is important that you request unique values each time. Do NOT copy the values shown below!

      Output

      define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

      These are configuration lines that we can paste directly in our configuration file to set secure keys. Copy the output you received now.

      Now, open the WordPress configuration file:

      • nano /var/www/your_domain/wp-config.php

      Find the section that contains the dummy values for those settings. It will look something like this:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'put your unique phrase here');
      define('SECURE_AUTH_KEY',  'put your unique phrase here');
      define('LOGGED_IN_KEY',    'put your unique phrase here');
      define('NONCE_KEY',        'put your unique phrase here');
      define('AUTH_SALT',        'put your unique phrase here');
      define('SECURE_AUTH_SALT', 'put your unique phrase here');
      define('LOGGED_IN_SALT',   'put your unique phrase here');
      define('NONCE_SALT',       'put your unique phrase here');
      
      . . .
      

      Delete those lines and paste in the values you copied from the command line:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
      define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');
      
      . . .
      

      Next, we need to modify some of the database connection settings at the beginning of the file. You need to adjust the database name, the database user, and the associated password that we configured within MariaDB.

      The other change we need to make is to set the method that WordPress should use to write to the filesystem. Since we've given the web server permission to write where it needs to, we can explicitly set the filesystem method to "direct". Failure to set this with our current settings would result in WordPress prompting for FTP credentials when we perform some actions. This setting can be added below the database connection settings, or anywhere else in the file:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('DB_NAME', 'wordpress');
      
      /** MySQL database username */
      define('DB_USER', 'wordpress_user');
      
      /** MySQL database password */
      define('DB_PASSWORD', 'password');
      
      . . .
      
      define('FS_METHOD', 'direct');
      

      Save and close the file when you are finished.

      Step 6 — Completing the Installation Through the Web Interface

      Now that the server configuration is complete, we can finish up the installation through the web interface.

      In your web browser, navigate to your server's domain name or public IP address:

      http://server_domain_or_IP
      

      Select the language you would like to use:

      WordPress language selection

      Next, you will come to the main setup page.

      Select a name for your WordPress site and choose a username (it is recommended not to choose something like "admin" for security purposes). A strong password is generated automatically. Save this password or select an alternative strong password.

      Enter your email address and select whether you want to discourage search engines from indexing your site:

      WordPress setup installation

      When you click ahead, you will be taken to a page that prompts you to log in:

      WordPress login prompt

      Once you log in, you will be taken to the WordPress administration dashboard:

      WordPress admin panel

      Conclusion

      WordPress should be installed and ready to use! Some common next steps are to choose the permalinks setting for your posts (can be found in Settings > Permalinks) or to select a new theme (in Appearance > Themes). If this is your first time using WordPress, explore the interface a bit to get acquainted with your new CMS, or check the First Steps with WordPress guide on their official documentation.



      Source link