
Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works?
Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works? If you are using Nodejs Copy and Paste the code on top after the import section
Technical Blogs & News
Fix Email Issues in CyberPanel with SMTP Relay Setup Free Method. First Create a email using your Cyberpanel Under Emai Tab Create Email Second go to the SSL tab and click …
You’ve probably seen many examples of password strength indicators around the web. They let users know the password they’re using is weak and indicate how the strength changes when it’s modified. …
Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works? If you are using Nodejs Copy and Paste the code on top after the import section
Fix the CORS Error — and How the Access-Control-Allow-Origin Header Works?
If you are using Nodejs Copy and Paste the code on top after the import section
router.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin",'*');
res.setHeader('Access-Control-Allow-Methods','POST,GET,OPTIONS,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');
next();
});
Install CKEditor on Strapi, In this guide, we will see how you can create a new Field for your administration panel Step1 Generate a plugin cd your-projectfolder Step2 Install the needed …
Install CKEditor on Strapi, In this guide, we will see how you can create a new Field for your administration panel
Step1
Generate a plugin
cd your-projectfolder
yarn strapi generate:plugin wysiwyg
Step2
Install the needed dependencies
cd plugins/wysiwyg
yarn add @ckeditor/ckeditor5-react @ckeditor/ckeditor5-build-classic
Step3
# Go back to strapi root folder
it will work only yarn, not npm. watch-admin help for project rebuilding automatically
cd ../..
yarn develop --watch-admin
Step4
Creating the MediaLib
Make folder components/MediaLib/index.js under ./plugins/wysiwyg/admin/src/
The path looks like that
./plugins/wysiwyg/admin/src/components/MediaLib/index.js
Then Paste the bellow code
import React, { useEffect, useState } from ‘react’;
import { useStrapi, prefixFileUrlWithBackendUrl } from ‘strapi-helper-plugin’;
import PropTypes from ‘prop-types’;
const MediaLib = ({ isOpen, onChange, onToggle }) => {
const {
strapi: {
componentApi: { getComponent },
},
} = useStrapi();
const [data, setData] = useState(null);
const [isDisplayed, setIsDisplayed] = useState(false);
useEffect(() => {
if (isOpen) {
setIsDisplayed(true);
}
}, [isOpen]);
const Component = getComponent(‘media-library’).Component;
const handleInputChange = data => {
if (data) {
const { url } = data;
setData({ …data, url: prefixFileUrlWithBackendUrl(url) });
}
};
const handleClosed = () => {
if (data) {
onChange(data);
}
setData(null);
setIsDisplayed(false);
};
if (Component && isDisplayed) {
return (
<Component
allowedTypes={[‘images’, ‘videos’, ‘files’]}
isOpen={isOpen}
multiple={false}
noNavigation
onClosed={handleClosed}
onInputMediaChange={handleInputChange}
onToggle={onToggle}
/>
);
}
return null;
};
MediaLib.defaultProps = {
isOpen: false,
onChange: () => { },
onToggle: () => { },
};
MediaLib.propTypes = {
isOpen: PropTypes.bool,
onChange: PropTypes.func,
onToggle: PropTypes.func,
};
export default MediaLib;
Step5
Creating the WYSIWYG Wrapper
Path ./plugins/wysiwyg/admin/src/components/Wysiwyg/index.js
Paste the below code in index.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { isEmpty } from 'lodash';
import { Button } from '@buffetjs/core';
import { Label, InputDescription, InputErrors } from 'strapi-helper-plugin';
import Editor from '../CKEditor';
import MediaLib from '../MediaLib';
const Wysiwyg = ({
inputDescription,
errors,
label,
name,
noErrorsDescription,
onChange,
value,
}) => {
const [isOpen, setIsOpen] = useState(false);
let spacer = !isEmpty(inputDescription) ? <div style={{ height: '.4rem' }} /> : <div />;
if (!noErrorsDescription && !isEmpty(errors)) {
spacer = <div />;
}
const handleChange = data => {
if (data.mime.includes('image')) {
const imgTag = `<p><img src="${data.url}" caption="${data.caption}" alt="${data.alternativeText}"></img></p>`;
const newValue = value ? `${value}${imgTag}` : imgTag;
onChange({ target: { name, value: newValue } });
}
// Handle videos and other type of files by adding some code
};
const handleToggle = () => setIsOpen(prev => !prev);
return (
<div
style={{
marginBottom: '1.6rem',
fontSize: '1.3rem',
fontFamily: 'Lato',
}}
>
<Label htmlFor={name} message={label} style={{ marginBottom: 10 }} />
<div>
<Button color="primary" onClick={handleToggle}>
MediaLib
</Button>
</div>
<Editor name={name} onChange={onChange} value={value} />
<InputDescription
message={inputDescription}
style={!isEmpty(inputDescription) ? { marginTop: '1.4rem' } : {}}
/>
<InputErrors errors={(!noErrorsDescription && errors) || []} name={name} />
{spacer}
<MediaLib onToggle={handleToggle} isOpen={isOpen} onChange={handleChange} />
</div>
);
};
Wysiwyg.defaultProps = {
errors: [],
inputDescription: null,
label: '',
noErrorsDescription: false,
value: '',
};
Wysiwyg.propTypes = {
errors: PropTypes.array,
inputDescription: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
PropTypes.shape({
id: PropTypes.string,
params: PropTypes.object,
}),
]),
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
PropTypes.shape({
id: PropTypes.string,
params: PropTypes.object,
}),
]),
name: PropTypes.string.isRequired,
noErrorsDescription: PropTypes.bool,
onChange: PropTypes.func.isRequired,
value: PropTypes.string,
};
export default Wysiwyg;
Step6
Implementing CKEditor
Path ./plugins/wysiwyg/admin/src/components/CKEditor/index.js
Paste the below code
import React from 'react';
import PropTypes from 'prop-types';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import styled from 'styled-components';
const Wrapper = styled.div`
.ck-editor__main {
min-height: 200px;
> div {
min-height: 200px;
}
}
`;
const configuration = {
toolbar: [
'heading',
'|',
'bold',
'italic',
'link',
'bulletedList',
'numberedList',
'|',
'indent',
'outdent',
'|',
'blockQuote',
'insertTable',
'mediaEmbed',
'undo',
'redo',
],
};
const Editor = ({ onChange, name, value }) => {
return (
<Wrapper>
<CKEditor
editor={ClassicEditor}
config={configuration}
data={value}
onReady={editor => editor.setData(value)}
onChange={(event, editor) => {
const data = editor.getData();
onChange({ target: { name, value: data } });
}}
/>
</Wrapper>
);
};
Editor.propTypes = {
onChange: PropTypes.func.isRequired,
name: PropTypes.string.isRequired,
value: PropTypes.string,
};
export default Editor;
At this point, we have simply created a new plugin that is mounted in our project but our custom Field has not been
registered yet.
Registering a our new Field
Path — ./plugins/wysiwyg/admin/src/index.js
import pluginPkg from '../../package.json';
import Wysiwyg from './components/Wysiwyg';
import pluginId from './pluginId';
import App from './containers/App';
import Initializer from './containers/Initializer';
import lifecycles from './lifecycles';
import trads from './translations';
export default strapi => {
const pluginDescription = pluginPkg.strapi.description || pluginPkg.description;
const icon = pluginPkg.strapi.icon;
const name = pluginPkg.strapi.name;
const plugin = {
blockerComponent: null,
blockerComponentProps: {},
description: pluginDescription,
icon,
id: pluginId,
initializer: Initializer,
injectedComponents: [],
isReady: false,
isRequired: pluginPkg.strapi.required || false,
layout: null,
lifecycles,
mainComponent: null,
name,
preventComponentRendering: false,
trads,
// menu: {
// pluginsSectionLinks: [
// {
// destination: `/plugins/${pluginId}`,
// icon,
// label: {
// id: `${pluginId}.plugin.name`,
// defaultMessage: name,
// },
// name,
// permissions: [
// // Uncomment to set the permissions of the plugin here
// // {
// // action: '', // the action name should be plugins::plugin-name.actionType
// // subject: null,
// // },
// ],
// },
// ],
//},
};
strapi.registerField({ type: 'wysiwyg', Component: Wysiwyg });
return strapi.registerPlugin(plugin);
};
Finally, you will have to rebuild strapi so the new plugin is loaded correctly
yarn build
// menu: {
// pluginsSectionLinks: [
// {
// destination: `/plugins/${pluginId}`,
// icon,
// label: {
// id: `${pluginId}.plugin.name`,
// defaultMessage: name,
// },
// name,
// permissions: [
// // Uncomment to set the permissions of the plugin here
// // {
// // action: '', // the action name should be plugins::plugin-name.actionType
// // subject: null,
// // },
// ],
// },
// ],
//},
This is a Laravel 8 JWT Authentication example tutorial. In this article, we will learn how to create secure REST APIs in Laravel using JSON Web Token (JWT). To protect user …
What is JSON Web Token?
JSON Web Token (JWT) is an open standard (RFC 7519), and it represents a compact and self-contained method for
securely transmitting information between parties as a JSON object. Digital signature makes the data Privacy transmission viaJWT trusted and verified. JWTs built upon the secret HMACalgorithm or a public/private key pair using RSA or ECDSA.
Why is JWT Required?
JWT is used for Authorization and information exchange between server and client. It authenticates the incoming
request and provides an additional security layer to REST API, which is best for security purposes.
Laravel 8 JWT Authentication Tutorial: User Login & Signup API
This is a comprehensive Laravel 8 JWT Authentication example tutorial. In this article, we will learn how to create
secure REST APIs in Laravel using JSON Web Token (JWT). To protect user authentication API in Laravel 8|7 we
will use tymondesigns/jwt-auth a third-party jwt-auth library.
Laravel 8 JWT Authentication Tutorial
Creating robust APIs in Laravel is secure, easy, and exciting. Laravel makes the development process relatively easy. It
takes out almost entire pain for developing comprehensive functionalities commonly used for web development, like
authentication, routing, sessions, and caching.
How does JWT Work?
User information such as username and password is sent to the webserver using HTTP GET and POST requests. The
web server identifies the user information and generates a JWT token and sends it back to the client. Client store that
token into the session and also set it to the header. On the next HTTP call, that token is verified by the server, which
returns the response to the client.
JSON Web Token Structure
JSON Web Tokens contain three parts separated by dots (.) In its dense form.
JWT similarly looks like this.
xxxxxx.yyyyyyy.zzzzzzzzzz
Install Laravel Application
Run the following command to install a fresh Laravel project
composer create-project laravel/laravel laravel-jwt-auth --prefer-dist
Database Connection and open .env in your project folder
DB_CONNECTION mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Add the single line of code below the database configuration in the .env file.
DB_HOST=localhost;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock
Add User into MySQL Database
In this step, we will learn how to register a user table in the MySQL database. Laravel fresh installation offers a default
user table that we can register into the database using migration.
php artisan migrate
The above command has created a users table inside the database
Install & Configure JWT Authentication Package
Execute the following command to install tymondesigns/jwt-auth, It is a third-party JWT package and allows user authentication using JSON Web Token in Laravel & Lumen securely.
composer require tymon/jwt-auth
The above command installed the jwt-auth package in the vendor folder, now we have to go to the config/app.php file
and include the laravel service provider inside the provider’s array.
Also include the JWTAuth and JWTFactory facades inside the aliases array.
'providers' => [
....
....
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
'aliases' => [
....
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory'
=>
Tymon\JWTAuth\Facades\JWTFactory::class,
....
],
In the next step, we have to publish the package’s configuration, following command copy JWT Auth files from vendor folder to config/jwt.php file.
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
For handling the token encryption, generate a secret key by executing the following command.
php artisan jwt:secret
We have successfully generated the JWT Secret key, and you can check this key inside the .env file.
JWT_SECRET=secret_jwt_string_key
Set Up User Model
Laravel comes with a pre-defined User model; we can use the User model for the authentication process. In this step,
we will learn how to implement the jwt-auth package in a user model.
Define Tymon\JWTAuth\Contracts\JWTSubject contract before the User model. This method wants you to define the
two methods:
Open the app/Models/User.php file and replace the following code with the existing code.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
Copyright © 2020-2021 techblog369.in Privacy Plolicyuse Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password','remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the identifier that will be stored in the subject claim
of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier() {
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims
to be added to the JWT.
*
* @return ©
array
*/
public function getJWTCustomClaims() {
return [];
}
}
Configure Auth guard
Now, we need to set up the JWT Auth Guard to secure the Laravel application’s authentication process. Laravel guard
uses the session driver to protect the guards. However, we set the defaults guard to API, and the API guards is ordered to use jwt driver.
Place the following code in config/auth.php file.
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
// 'guards' => [
// 'web' => [
// 'driver' => 'session',
// 'provider' => 'users',
// ],
// ],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
Build Authentication Controller
In this step, we will create the JWT authentication controller, and in this auth controller, we will define the core logic for the secure authentication process in Laravel 8.
Let us define the auth controller manually or by using the below command to manage the authentication requests via
routes that we created in the previous step.
php artisan make:controller AuthController
Place the following code app/Http/Controllers/AuthController.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Validator;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
// public function login(Request $request){
// $this->validate($request, [
// 'email'=> 'required|max:32',
// 'password'=> 'required|max:32|min:8',
// ]);
// if (Auth::attempt(['email'=>$request->email,'password'=>$request->password])) {
// $user = users::where('email','=',$request->email)->first();
// return redirect('/messenger')->with('usersignin');
// }
// return "ooopps something wrong";
// }
/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh() {
return $this->createNewToken(auth()->refresh());
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function userProfile() {
return response()->json(auth()->user());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
// 'expires_in' => auth('web')->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
}
The auth: API middleware is used within the constructor; functions inside the authentication controller can not be
accessed without having the valid token. Also, we can pass the functions name inside the middleware that we want to
exclude from the token obligation.
The login method is used to provide access to the user, and it is triggered when /API/auth/login API is called. It
authenticates the email and password entered by the user in an email and password field. In response, it generates an
authorization token if it finds a user inside the database. Viceversa it displays an error if the user is not found in the
database.
The register method is used to create a user when /API/auth/register route is called. First, user values such as
name, email, and password are validated through the validation process, and then the user is registered if the user
credentials are valid. Then, it generates the JSON Web Token to provide valid access to the user.
The logout method is called when /API/auth/logout API is requested, and it clears the passed JWT access token.
The refresh method creates a new JSON Web Token in a shorter period, and It is considered a best practice to
generate a new token for the secure user authentication system in Laravel 8|7. It invalidates the currently logged-in
user if the JWT token is not new.
The user profile method renders the signed-in user’s data. It works when we place the auth token in the headers to
authenticate the Auth request made through the /API/auth/user-profile API.
The create new token function creates the new JWT auth token after a specified period of time, we have defined token expiry and logged in user data in this function.
Add Authentication Routes
We need to define the REST API authentication routes for auth process in Laravel JWT Authentication application. The routes that are served through routes/api.php are prefixed with api/ and authentication routes are denoted by auth/.
So it becomes /API/auth/signup, and it goes the same for every route we have created for authentication.
We need to add authentication routes in routes/api.php instead of web.php:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/refresh', [AuthController::class, 'refresh']);
Route::get('/user-profile', [AuthController::class, 'userProfile']);
});
Test Laravel JWT Authentication API with Postman
Start the laravel application with following command:
php artisan serve
We have created a secure REST API using JWT Authentication. To make the testing process easy and subtle,
we will rely on Postman.
Authentication APIs for Login, Register, User Profile, Token Refresh, and Logout.
POST /api/auth/register
POST /api/auth/login
GET /api/auth/user-profile
POST /api/auth/refresh
POST /api/auth/logout
User Registration API in Laravel
Open the Postman, and add the user registration API in the address bar, and select the HTTP request method to POST. Select the form-data and add the name, email, password, and password confirmation values in the input fields. Click on the Send button to see the response coming from the server.
Test Laravel Login API
To test login API in Laravel with the JWT Authentication token, add the email and password details in the input fields
and click on the Send button. You can see on successful login a JWT access token, token type, token expiration time,
and user profile details returned.
User Profile
Make sure you must define the access token as a header field “Authorization: Bearer Token” for User Profile, Token
Refresh, and Logout REST APIs.
JWT Token Refresh in Laravel
To refresh a token We must have a valid JWT token, you can see we are getting the access_token and user data in
Postman response block.
Logout
We destroyed the JWT token on logout and you can use Postman to test the Logout API as follows.
Thanks for reading….
Download from GitHub
Introduction Are you looking for a way to deploy your Nuxt.js website or application?In this article, we’ll walk you through how to deploy a production-ready Nuxt.js website to a DigitalOcean server. …
I assumed that you have already NuxtJs Project
Table of Contents
Create & Configure a DigitalOcean Server
Before anything else, we need to create and configure the server in the cloud using DigitalOcean.
To start, you’ll need to create an account on DigitalOcean or log in to your existing account.
Create a New Droplet On DigitalOcean
After logging in or successfully signing up for a new account, open the “Create” drop-down menu and click the “Droplets” link.
This will take you to the “Create Droplets” page where you’ll be given some configuration options before creating a new server.
In the first section, select the Ubuntu operating system for your server.
I have selected a 5$ per month standard plan
Next, they allow you to choose the data center region for your server. This is the physical location for your server and, therefore, you should choose the one closest to the people visiting your website.
In the “Authentication” section, make sure the “Password” option is selected and enter a strong root password for your server. This is the password we’ll use to initially SSH into your server.
##Note: Make sure you save this password because you’ll need it to gain initial access to your server.
Also, you can choose a hostname for your server. This will give your server a name to remember it by.
When you’re done selecting options, hit the “Create Droplet” button to kick off the creation of your new server.
When the Droplet is fully up and running, the control panel will display the server’s IP address.
Your server is now up and running!
In the next step, we’ll complete the initial configuration process for the server. This will include logging into the server, setting up SSH access to the server, and creating a basic firewall.
Configure Your New Server Droplet
Right now, your server is a blank machine humming along on a server rack in your geographic region of choice.
In this section, we’ll walk through how to gain remote access to the server and set up some basic configurations to help keep it secure before we deploy and run your Next.js application on it.
Via the terminal, we’ll be switching back and forth between the server we create and your local machine. So, pay close
attention to what environment you’re in before running commands throughout this article.
Let’s get started!
Access Server Using Root
The first step is to gain access to the server using your root login.
To do this, you’ll need both the IP address of the server and the private key (password) for the root user’s account you created in the last section.
To log into your server, open a terminal on your local machine and use the following command to SSH in as the root user (insert your server’s IP address in place of server_ip_address ):
$ ssh root@server_ip_address
If a warning about host authenticity appears, accept it.
Then, provide the root password you created.
After you’ve successfully logged in, you should be remotely inside your DigitalOcean server.
The root user in a Linux environment has very broad privileges and, for that reason, you’re discouraged from using it regularly. This is because very destructive changes (even by accident) can be made while using it.
Therefore, in the next step, we’re going to create an alternative account with limited scope that will be used for daily tasks.
Create A New User
Logged in as root, we can create a new user account that will be used to log in from this point forward.
You can create a new user with the following command (insert a username you want in place of username ):
root@hostname:~# adduser username
You’ll be asked some questions starting with the password. Make sure you choose a strong password.
The rest of the question prompts are optional. You can just hit ENTER repeatedly to skip them if you wish.
You now have a new user account with regular account privileges. But you might occasionally need to do administrative tasks that require root privileges. So, instead of logging out of your normal
user and logging back in as the root account, we can give the normal account the ability to run root privileged commands when you need to by adding sudo before each command.
To do this, we need to add your new user to the sudo group on
the machine. As root, run the following command to add your user to the group (replace username sudo with your username):
root@hostname:~# usermod -aG sudo username
Now your user can run commands with root privileges!
The next initial server setup steps will help increase the security of your server. They are optional but highly recommended.
Add Public Key Authentication
By setting up public-key authentication for the new user, it will increase your server’s security by requiring a private SSH key to login in instead of anyone being able to access the server via password.
Let’s get pubic key authentication configured.
Generate a Key Pair on Your Local Machine
If you don’t already have an SSH key pair on your local machine, which consists of a public and private key, you need to generate one. If you already have a key that you want to use, skip to the Copy the Public Key step below.
To generate a new key pair, enter the following command at the terminal of your local machine:
$ ssh-keygen
You’ll receive an output similar to the following:
pallab@pallab-NE572:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/pallab/.ssh/id_rsa):
Press ENTER to accept the file name and path.
Next, you’ll be prompted to enter a password to secure the newly created key. You can either create a password or leave it blank. This generates a private key, id_rsa.pub, in the /.sshid_rsa, and a public key, directory inside your home directory.
Copy The Public Key
Now that you have the SSH key pair configured on your local machine, you need to copy your public key to the server.
Use one of the two options below to do this.
Option 1: Use SSH-Copy-Id
If your local machine has the ssh-copy-id script installed, you can use it to install your public key for any user that you have login credentials for. If your machine doesn’t have the script, use the second option to install the key manually instead.
Still, on your local machine, type the following command (replace your username and IP address for the values below):
$ ssh-copy-id bob@server_ip_address
You’ll be asked for the user’s password.
This is the password for the user you created on your server. Not the root password.
After successfully authenticating, your public key will be added to the server user’s .ssh/authorized_keys file. The corresponding private key can now be used to log into the server.
Option 2: Install The Key Manually
Assuming you generated an SSH key pair using the previous step, use the following command at the terminal of your local machine to print and display your public key ( id_rsa.pub ):
$ cat ~/.ssh/id_rsa.pub
This should print your public SSH key, which should look something like the following:
Output
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBGTO0tsVejssuaYR5R3Y/i73
Select the public key in the terminal output, and copy it to your clipboard.
To enable the use of the SSH key to authenticate as the new remote user, you must add the public key to a special file in the user’s home directory.
Back on your DigitalOcean server, as the root user, enter the following command to temporarily switch to the new user (substitute your username in place of username ):
root@hostname:~# su - username
Now you’ll be in your new user’s home directory.
Create a new directory called /.ssh :
username@hostname:~$ mkdir ~/.ssh
And restrict its permissions with this command:
username@hostname:~$ chmod 700 ~/.ssh
Now open a file in We will use nano .ssh called authorized_keys with a text editor. to edit the file:
username@hostname:~$ nano ~/.ssh/authorized_keys
Now insert the public key you generated and copied by pasting it into the nano editor
Hit + X to exit the file, then CTRL made, then. ENTER Y to save the changes that you to confirm the file name.
Now restrict the permissions of the authorized_keys file with this command:
username@hostname:~$ chmod 600 ~/.ssh/authorized_keys
Type this command once to return to the root user:
username@hostname:~$ exit
Now your public key is installed, and you can use SSH keys to log in as your user.
Disable Password Authentication
This step will configure your DigitalOcean server to only allow logins using the SSH key you just created. Therefore, only people who possess the private key that pairs with the public key that was installed will get into the server. This increases your server’s security by disabling password-only authentication.
Only follow this step if you installed a public key in the last step. Otherwise, you’ll lock yourself out of the server.
To disable password authentication, follow the proceeding steps.
As the root user or new sudo user on your DigitalOcean server, open the SSH daemon configuration file using the following command:
bob@hostname:~# sudo nano /etc/ssh/sshd_config
Find the line that says PasswordAuthentication keyboard keys) and change its value from yes (using the arrow to no. It should look like this after the change was made:
/etc/ssh/sshd_config
PasswordAuthentication no
Save and close the file using this method: ENTER CTRL-X , then Y , then Enter.
To reload the SSH daemon and put the changes live, execute the following command:
username@hostname:~# sudo systemctl reload sshd
Password authentication is now disabled. Now your server can only be accessed with SSH key authentication.
Let’s test logging in using the SSH key.
On your local machine, log in to your server using the new account that we created. Use the following command to do so (substitute your username and IP address):
ssh username@server_ip_address
Once authentication is provided to the server, you’ll be logged in as your new user.
Now your server is only accessible by someone who has the SSH keys you generated. Which, in this case, are only located on your local machine. This greatly improves the security of your server.
Add a Basic Firewall
Another security improvement we can make to the server is to add a basic firewall.
Ubuntu servers can use the UFW firewall to ensure only connections to certain services are allowed. It’s a simple process to set up a basic firewall and will further improve your server’s security.
You can see which applications UFW currently allows by typing
username@hostname:~$ sudo ufw app list
This should output the following: Output
Available applications
OpenSSH
We need to make sure the firewall allows SSH connections so that we can log back in next time. To allow these types of connections, type the following command:
username@hostname:~$ sudo ufw allow OpenSSH
And then enable the firewall:
username@hostname:~$ sudo ufw enable
Press y and then ENTER to proceed.
You can see that SSH connections are still allowed by typing:
username@hostname:~$ sudo ufw status
The OpenSSH directive should be listed.
That was the last step in the initial setup for our server. Our server is now configured and ready to go!
In the next section, we’ll configure your domain name.
Configure a Domain Name
In this section, we’ll configure a domain name that you want to use for your Nuxt.js website.
To set up a domain, you’ll need to do two things:
DigitalOcean is not a domain name registrar, which means you can’t purchase a domain name from them. But, they do provide a DNS hosting service that makes it easy to configure a domain name with their servers.
Before proceeding, make sure you have purchased a domain name from a service like GoDaddy, namecheap, HostGator,test.com, or another registrar.
Let’s get started!
Configure DigitalOcean DNS For Your Domain
Using DigitalOcean, let’s configure DNS for your domain.
Back on the DigitalOcean website, open the “Create” drop-down menu and click the “Domains/DNS” link.
In the “Add A Domain” section, enter your domain (this is usually the base only: example.com and not www.example.com ) and click the “Add Domain” button.
Once you’ve hit the “Add Domain” button, you’ll be taken to the “Create new record” page.
You now need to add NS records for the domain on DigitalOcean’s systems. You’ll only be adding A records, which
maps an IPv4 address to a domain name. This will determine where DigitalOcean should direct any requests for your domain name to.
We want your website to be accessible at two different base
URLs:
For the first one, enter @ in the HOSTNAME field and select the server you want to point the domain name to:
For the second one, enter www in the HOSTNAME field and select the same server:
Awesome, we can move on to the next step.
Configure Your Domain Registrar To Direct Domains to DigitalOcean
To use the DigitalOcean DNS, you’ll need to update the nameservers used by your domain registrar to point to
DigitalOcean’s nameservers instead.
In the “Nameservers” section of the resulting screen, select Custom DNS from the dropdown menu and enter the following nameservers:
This process usually takes about 30 minutes but could take up to a few hours depending on your registrar and your ISP’s communication methods.
Now that your domain is pointing to your server, it’s time to install Nginx and configure it as a reverse proxy so your Next.js
Let’s get Nginx configured on your server.
Install Nginx
On your DigitalOcean server, run the following commands to update your local apt package index so we have access to the most recent package lists and install the Nginx software:
username@hostname:~$ sudo apt-get update && sudo apt-get install nginx
The apt-get command will install Nginx along with any other required dependencies.
When those commands finish, Nginx will be available for you to use on the server.
Before we can use Nginx, we need to reconfigure our firewall software to allow access to the service. Nginx registers itself as a service with ufw, our firewall, upon installation. This makes it rather easy to allow Nginx access.
We can list the applications configurations that ufw knows how to work with by typing:
sudo ufw app list
You should get a listing of the application profiles:
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
There are three profiles available for Nginx:
It’s recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Since we haven’t configured SSL for our server yet, we’ll only need to allow traffic on port 80. When we set up SSL Encryption, later on, we’ll change these settings.
You can enable this by typing:
sudo ufw allow 'Nginx HTTP'
You can verify the change with this command:
sudo ufw status
You should see Nginx HTTP listed in the output.
The Nginx web server should already be up and running.
To make sure the service is running, execute this command:
systemctl status nginx
output
nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2016-04-18 16:14:00 EDT; 4min 2s ago
Main PID: 12857 (nginx)
CGroup: /system.slice/nginx.service
├─12857 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
└─12858 nginx: worker process
You can access the default Nginx landing page to confirm that the software is running properly. This can be accessed through your server’s domain name or IP address in the browser.
When you have your server’s IP address or domain, enter it into your browser’s address bar: http://server_domain_or_ip_address.
You should see the default Nginx landing HTML page, which should look something like this:
You now have an Nginx web server running on your server that is accessible to the world!
We’ll come back to Nginx later on in this section when we create a reverse proxy for your application.
To run your Next.js application, you’ll need to have Node.js installed on your DigitalOcean server. Furthermore, you’ll need to have Node.js version 10.13 or later for Next.js to work properly.
To make things easy, we’ll use the NodeSource package archives to install Node.js.
First, you need to install the NodeSource PPA (Personal Package Archive) to get access to its contents. Make sure you’re in the home directory on your DigitalOcean server:
# Using Ubuntu
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
The nodejs package contains the nodejs binary as well as NPM, so you won’t need to install NPM separately. But for some NPM packages to work, you’ll need to install the build-essential package
sudo apt-get install build-essential
When that is done installing, Node.js should be fully installed and ready to use on your server.
You can test this by verifying the version of Node.js on your machine:
node --version
npm --version
In the next sections, we’ll use Node.js and NPM to configure and run your Nuxt.js application.
I assumed that you have already had Nuxt.js Project
To deploy your Nuxt.js website, we’ll need to push the code for your project to GitHub (or Gitlab) and pull it into our DigitalOcean server. Then we’ll run the application in production mode and keep it running forever using the PM2 NPM package.
Let’s push the project code for your Next.js application to GitHub.
We need to first create a repository on GitHub that you can upload the code to.
First, go to https://github.com.
If you don’t have a GitHub account, you’ll need to create one.
Once you’re logged in or signed up, click the Start a Project button or navigate to the Create a New Repository page.
After you press the Start a Project button, you’ll be redirected to another page where you can name your repository, give it a description, and more.
When you’re done filling out the form, press the Create Repository button.
You should now have an empty repository created on GitHub!
Now we can add some code to our repository.
On your local machine, navigate to the root directory of your project.
cd your-project
git init
git remote add origin https://github.com/your_github_username/your_repository_name.git
Before we push the code to GitHub (or Gitlab), we need to add a .gitignore file to our project. This will instruct Git to not commit certain files or directories of a given name or type.
In the root of your project directory, create a .gitignore file:
touch .gitignore
/your-project/.gitignore
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
.next
Now, we can commit and push our project code without causing problems like committing our entire node_modules file.
Tell Git to stage all the files in the project folder with this command:
git add .
git commit -m "Initial commit."
git push origin master
Once you’ve successfully entered your GitHub account credentials and the push process is finished, head over to GitHub and view your repository. You should see the code has been pushed and is now visible.
Your application is now ready to pull onto the server.
We’re now ready to get your Next.js application up and running on your DigitalOcean server.
First, we’ll pull in the code we just pushed to GitHub and then we’ll get the application running.
On your DigitalOcean server, make sure you are located in the home directory:
username@host:cd ~
username@host: git clone https://github.com/your_github_username/your_repository_name.git frontend
If you made your repository private, it’ll ask for your GitHub username and password credentials before it initiates the cloning process.
The frontend portion of the command will ensure the name of the project folder created is /frontend.
When the clone is complete, cd into the new /frontend directory:
cd frontend
npm install
npm run dev
You shouldn’t encounter any errors and the terminal should output the same message as it did when we were in development mode on your local machine:
output
ready - started server on http://localhost:3000
Stop the application with the CTRL+C keyboard shortcut.
Now that we know everything is working, we need to use the npm run build function from the package.json file to create a production version of the Next.js application.
Still, in the root of the /frontend project directory, execute this command:
npm run build
This command may take a minute to complete.
When it’s complete, a new /.next folder will be created in your project directory. The production version of your website will be run using the code in that folder.
When we run the application in production mode, we’ll use the npm start command (instead of the npm run dev). So, let’s start the application using that command:
npm start
output
Ready on http://localhost:3000
Awesome! Your frontend website Next.js application is up and running on the server!
But how do we keep the application running forever, even if errors occur or in the rare scenario the entire machine needs to be restarted? In the next section, we’ll introduce the PM2 NPM package to help us with that.
You’re now ready to install and configure PM2, which is a process manager for Node.js applications. It will allow you to keep your Node.js application alive forever, reload it without any downtime and help facilitate common system administrative tasks.
Install the PM2 NPM package globally on your DigitalOcean machine with this command:
username@host:~$ sudo npm install -g pm2
The -g option tells NPM to install the package globally. It’ll now be available across your server’s entire system.
Now we want to run the Next.js website application using PM2.
First, make sure you’ve navigated into the /frontend project directory:
username@host:~$ cd frontend
Then, use this command to run the application with PM2:
username@host:~$ pm2 start --name=website npm -- start
This will start your Next.js application and then display a table with its name, process ID, status, CPU usage, etc.
PM2 automatically adds an App Name and PM2 id to your application, along with other information such as the PID of the process, its current state, and memory usage.
The specific command we used gives the application the name of frontend within PM2. This will help us easily identify all the applications running within PM2 as we add more.
PM2 applications will be restarted automatically if the application crashes or is killed. But additional steps need to be taken for applications to start on system startup (reboot or boot). PM2 provides an easy way to do this with its startup command.
Run it with the following command:
username@host:~$ pm2 startup systemd
On the last line of the resulting output, there will be a command that you must run with superuser privileges:
[PM2] Init System found: systemd
[PM2] You have to run this command as root. Execute the following command:
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username
Copy and paste the command that was generated (same as above but with your username instead of bob) to have PM2 always start when your server is booted.
Your command will look similar to this:
username@host:~$ sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username
This will create a system unit that will run PM2 for your user on boot. This PM2 instance, in turn, will run all the applications configured to run using PM2. To check the status of the new system unit, use the following command:
username@host:~$ systemctl status pm2-username
Your Nuxt.js website application is now up and running on port 3000 and will run forever, or until you tell PM2 to stop.
In the future, you’ll most likely need to push new code updates. To do so, you can follow these steps:
In the next section, we’ll setup a Nginx reverse-proxy in front of your Next.js application to make it accessible to the world.
Configure Nginx As A Reverse Proxy
Now that your application is running and listening on localhost:3000, we need to make it so people from the outside world can access it. To achieve this, we will use Nginx as a reverse proxy.
On Debian systems (i.e. Ubuntu), Nginx server configuration files are stored in /etc/nginx/sites-available directory, which are enabled through symbolic links to the /etc/nginx/sites-enabled directory.
Therefore, we need to create a configuration file in the /etc/nginx/sites-available directory that will instruct Nginx how to serve our application and at what URLs to serve it to.
First, navigate to the /etc/nginx/sites-available directory:
username@host:~$ cd /etc/nginx/sites-available
Then, create a new configuration file for your website (you’ll need to use sudo for any changes you make in these configuration files):
username@host:~$ sudo touch example.com
To keep things organized, we suggest naming each Nginx configuration file after the URL they’re created for.
Open that file for editing using nano:
username@host:~$ sudo nano example.com
And add this code to the file:
/etc/nginx/sites-available/example.com
server {
listen 80;
listen [::]:80;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}
These are the contents of the default Nginx configuration file, but with all the commented-out lines removed for brevity. Also, the default_server designation for the listen to directives (listed 80; and listen [::]:80;) are removed. Only one server block can have the default_server option enabled, which is already occupied by the /sites-available/default configuration file.
The first thing we need to modify in this file is the domain URL and any other aliases to match requests. To do this, replace the server_name _; line with the following:
default Nginx file
/etc/nginx/sites-available/default
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
# Default server configuration
#
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# proxy_pass http://localhost:8080;
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection 'upgrade';
# proxy_set_header Host $host;
# proxy_cache_bypass $http_upgrade;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
# fastcgi_pass unix:/run/php/php7.0-fpm.sock;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#
/etc/nginx/sites-available/example.com
server_name example.com www.example.com;
Make sure you replace example.com and www.example.com with your URLs.
This configuration file is also telling Nginx to serve the content of the /var/www/html directory, which is a default file generated by Nginx. To change that to instead serve our Next.js application running on localhost:3000, update the location section to this: /etc/nginx/sites-available/example.com
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
With those settings, Nginx will serve the application running at http://localhost:3000, which we just finished configuring in the last section.
When you’re done, the entire file should look similar to this:
server {
listen 80;
listen [::]:80;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Save and exit the file when you’re finished making changes.
Now that we have the server block file created, we need to enable it. We can do this by creating symbolic links from these files to the /sites-enabled directory, which Nginx reads from during startup.
We can create the symbolic link with this command:
username@host:~$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Make sure you replace the example.com portion of the command with the name of your configuration file.
Your configuration file is now symbolically linked to the /sites-enabled directory.
To avoid a hash bucket memory problem in the future when we add additional applications, we need to adjust a single line in the /etc/nginx/nginx.conf file.
Open the file using nano:
username@host:~$ sudo nano /etc/nginx/nginx.conf
In that file, find a commented out line that reads # server_names_hash_bucket_size 64; and remove the comment # symbol to uncomment the line:/etc/nginx/nginx.conf
http { . . . server_names_hash_bucket_size 64; . . . }
Save and close the file when you’re done.
Next, use the nginx -t command to test that there are no syntax errors any of the Nginx files you just edited or created:
sudo nginx -t
sudo systemctl restart nginx
Nginx should now be serving the Next.js application at your domain (www.example.com).
Open a browser and navigate to your domain. You should see your website!
In the next section, we’ll set up SSL encryption so your website can be served over https://.
Next, we’ll use both the Let’s Encrypt service and the Certbot software to obtain and install free SSL certificates for the example.com and www.example.com URLs.
Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free SSL certificates, thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps.
Let’s get it done!
Install Certbot
First, we need to install the Certbot software on your server.
You can add the repository to your machine with this command:
username@host:~$ sudo add-apt-repository ppa:certbot/certbot
You’ll need to press ENTER to accept.
Then, update the package list on your machine to pick up the Certbot repository’s package information:
sudo apt-get update
sudo apt install python3-certbot-nginx
The Certbot software is now ready to use on your server.
Previously, we configured the ufw firewall on your server to allow HTTP traffic. To additionally let in HTTPS traffic, we need to allow the Nginx Full profile and then delete the redundant Nginx HTTP allowance.
Here is the command to allow Nginx Full:
sudo ufw allow 'Nginx Full'
And here is the command to delete the redundant Nginx HTTP profile:
sudo ufw delete allow 'Nginx HTTP'
We’re now ready to run Certbot and configure SSL certificates for your website.
Certbot provides a variety of ways to obtain SSL certificates, through various plugins. The Nginx plugin will take care of reconfiguring Nginx and reloading the Nginx configuration files whenever necessary.
To get SSL certificates for your example.com and www.example.com URLs, use this command (make sure to use your URLs):
sudo certbot --nginx -d example.com -d www.example.com
This command runs certbot with the –nginx plugin and also uses the -d directive to specify the names we want certificates to be valid for.
Since this is the first time you’ve run Certbot on the machine, you’ll be prompted to enter an email address and asked to agree to the terms of service.
After doing so, Certbot will communicate with the Let’s Encrypt server, then run a challenge to verify that you control the domain you’re requesting a certificate for.
If that’s successful, Certbot will ask how you’d like to configure your HTTPS settings.
output
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. ------------------------------------------------------------------------------- 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. ------------------------------------------------------------------------------- Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
The redirect option (Option 2) is the suggested choice. Select your choice then hit ENTER. The configuration will be updated, and Nginx will reload to pick up the new settings.
Your certificates are now downloaded, installed, and loaded. Go to your browser window and try reloading the website using https:// instead. The site should now be served using https://.
The last thing we need to do is test the certificate renewal process.
Let’s Encrypt’s certificates are only valid for ninety days. This is to encourage users to automate their certificate renewal process.
The certbot package we installed takes care of this for us by running certbot renew twice a day via a systemd timer. On non-systemd distributions, this functionality is provided by a script placed in /etc/cron.d. This task runs twice a day and will renew any certificate that’s within thirty days of expiration.
To test the renewal process, you can do a dry run with certbot:
sudo certbot renew --dry-run
If you don’t see any errors, you’re good to go!
When needed, Certbot will renew your certificates and reload Nginx to pick up the changes. If the automated renewal process fails, Let’s Encrypt will send a message to the email you specified, warning you when your certificate is about to expire.
Your Nuxt.js website is now fully deployed!
Thanks for reading
In this article, I am showing how to create a non-root user on Ubuntu 20.04Server. How to create a non-root user on Ubuntu 20.04 Server. I have already installed Ubuntu Server …
In this article, I am showing how to create a non-root user on Ubuntu 20.04Server.
We will use an SSH Client to get access to the server’s terminal (this remote computer), and once we have access
to the terminal, we can start executing commands on this server. You can also use putty software for the same, but in
this article, I am using SSH Client.
Execute the following command on the PowerShell or terminal
ssh root@your_server_ip
Enter the password provided by your service provider. We have created a password in DigitalOcean, which we will
enter here. Once you enter the password when prompted, you will be logged in as root.
The root user is a user having the highest privileges on the server. This means that a root user can do anything and
everything on the server. This is why it is strongly discouraged to use a root account as it might accidentally
delete files/uninstall programs/install programs etc. Hence we will create a user who will have restricted permissions on the server for day-to-day use.
Creating a non-root user
Now we are creating the non-root user Execute following command
You will be asked to enter some information and a password. Choose a strong password to avoid getting hacked!
We have successfully created an account with basic access. We want this user to be able to elevate to root access when required. This will be useful when you want to use your server and sometimes do something which requires root
access.
Execute the following command on the server:
Firewall setup
Our server is public, and we want to protect it from external unwanted connections. We want only selected services
exposed to the public on our server.
We will set up the UFW firewall on our Ubuntu 20.04 server and allow OpenSSH, which allows us to connect to our
server.
Execute the following command to allow OpenSSH:
The firewall will now block all the connections except SSH
You have successfully created a new user. Try to log in through this user in a new terminal tab and verify everything
works before logging out from the current session.
You can type the following command to elevate to the root access as and when required.
Note: Please check is successfully user-created or not, So open a new terminal and paste the below code
You have finished creating your HTML website and you’re feeling proud of your hard work. But there is one thing that is still missing: you have no idea how to publish …
You have finished creating your HTML website and you’re feeling proud of your hard work. But there is one thing that is still missing: you have no idea how to publish your website.
In this tutorial, you will learn how to publish an HTML website using two popular platforms – Netlify and GitHub.
Before we start, make sure that you have a GitHub account because you will need to host your repository (your source code) on GitHub. Without it, you won’t be able to publish your HTML website following this tutorial.
How to Publish a Website on Netlify
The first method we’re going to explore is how to publish your website on Netlify.
Netlify is a platform for hosting websites. It is easy to host sites on Netlify as you don’t need to configure it manually – and best of all, it’s free. If you haven’t signed up for an account, now is a good time to do so.
Here’s the step-by-step process of publishing your website on Netlify:
Step 1: Add your new site
Once you’ve logged in, it will take you to a home dashboard. Click the New site from git button to add your new website to Netlify.
Step 2: Link to your GitHub
When you click the New site from git button, it will take you to the “Create a new site” page. Make sure that you push your repository on GitHub so that Netlify can link to your GitHub account.
Click the GitHub button as shown in the screenshot below:
Step 3: Authorize Netlify
Next, click the Authorize Netlify by Netlify button. This permission is needed so that both Netlify and GitHub can connect.
Step 4: Select your repository
Once you grant permission to Netlify, you can see a list of all your repositories. Select your website to publish. You can find it by either scrolling down the list or using the search bar to narrow down the list.
Step 5: Configure your settings
After selecting your website, you will be prompted to configure the settings for deploying the website. Since your website is simply a static one, there’s not much to do here. Just click Deploy site to continue.
Step 6: Publish your website
Your website is now ready to publish! Netlify will do the rest of the work for you, and it will only take a minute or so to complete the process.
Now you are done! Your new website is published, and you can view it by clicking the green link.
Right now, your URL looks random, but you can edit it by clicking the Site settings button and then the Change site name button.
Congratulation on publishing your first new website.
How to Publish a Website on GitHub
The second method we’ll look at uses GitHub to publish your site. GitHub is a platform for storing, tracking, and managing project source code. It is also where you can publish your HTML website – and like Netlify, it is free to host here.
Here’s the step-by-step process of publishing your website on GitHub:
Note: You can only publish your website on GitHub if you set the repository’s visibility to the public. If you want to deploy a website while it is private, upgrade your account to Pro or use Netlify to host there instead.
After you’ve logged in, go to the repository on the left sidebar and select the one you want to publish.
In your repository, click the Settings link, and it will take you to the repository’s settings page.
When you’re in a repository’s settings, scroll down a bit until you see the Pages link on the left sidebar. Click it, and it will lead you to GitHub Pages
In the source section, click the dropdown and select the master branch and save it. Depending on how you name it, it can be master or main.
And you are done! Your website will be published, and it will take only a minute or so to complete the process. Refresh the page, and you will see a link to your newly published website.
I hope you’ve found this tutorial helpful. You have learned how to publish your HTML website with Netlify and GitHub. Now you can go ahead and show the world of your incredible work.
Automatically generate or serve dynamic sitemap.xml for Nuxt.js projects! Hi In this Article I will show how to configure dynamic Sitemap in NuxtJS Hope you have already the NuxtJs Project here …
Automatically generate or serve dynamic sitemap.xml for Nuxt.js projects!
Hope you have already the NuxtJs Project here I am only showing the Sitemap configuration. Lets Start
npm install @nuxtjs/sitemap
or
yarn add @nuxtjs/sitemap
Once successfully installed you can check your package.json file under dependencies @nuxtjs/sitemap installed
Then go to the nuxt.config.js file and add the modules.
modules: [
// https://go.nuxtjs.dev/axios
'@nuxtjs/axios',
//'vue-social-sharing/nuxt',
'@nuxtjs/sitemap'
],
Then Import Axios into the nuxt.config.js file on the top
const axios = require('axios')
Then you have to create a sitemap.xml file in a root folder
To declare a sitemap index and its linked sitemaps, use the sitemaps property.
sitemap: {
hostname: 'your website url',
gzip: true,
exclude: [
],
routes: async () => {
let { data } = await axios.get('https://yourapi/articles')
return data.map(v => `/blog/${v.slug}`)
}
},
http://localhost:3000/sitemap.xml
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:news="http://www.google.com/schemas/sitemap-
news/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:mobile="http://www.google.com/schemas/sitemap-
mobile/1.0"
xmlns:image="http://www.google.com/schemas/sitemap-
image/1.1"
xmlns:video="http://www.google.com/schemas/sitemap-
video/1.1">
<url>
Copyright © 2020-2021 techblog369.in Privacy Plolicy
<loc>https://localhost:3000/blog/token-authentication-requirements-for-git-operations</loc>
</url>
<url>
<loc>https://localhost:3000//blog/how-to-migrate-or-
configure-word-press-database-from-one-hosting-server-to-
another-server</loc>
</url>
<url>
<loc>https://localhost:3000//blog/how-to-install-ck-editor-
on-strapi</loc>
</url>
<url>
<loc>https://localhost:3000/blog/how-to-remove-html-and-
php-extension-from-url-using-htaccess</loc>
</url>
<url>
<loc>https://localhost:3000/blog</loc>
</url>
<url>
<loc>https://localhost:3000/news</loc>
</url>
<url>
<loc>https://localhost:3000/</loc>
</url>
</urlset>
In this article, I will show How to Migrate or Configure WordPress databases from one hosting Server to another Server? Here I am only showing Database Configuration First, you have to …
In this article, I will show How to Migrate or Configure WordPress databases from one hosting Server to another Server?
Here I am only showing Database Configuration
UPDATE wp_posts SET guid = REPLACE(guid, 'oldurl.com', 'newurl.com') WHERE guid LIKE 'http://oldurl.com/%';
UPDATE `wp_posts` SET guid = REPLACE(guid, 'oldsiteurl', 'newsiteurl') WHERE guid LIKE 'oldsiteurl%';
UPDATE `wp_postmeta` SET meta_value = REPLACE(meta_value, 'oldsiteurl', 'newsiteurl') WHERE meta_value LIKE 'oldsiteurl%';
UPDATE `wp_options` SET option_value = REPLACE(option_value, 'oldsiteurl', 'newsiteurl') WHERE option_value LIKE 'oldsiteurl%';
If you got any plugins that do redirections you should also change the permalinks there:
UPDATE `wp_redirection_404` SET url = REPLACE(url, 'oldsiteurl', 'newsiteurl') WHERE url LIKE 'oldsiteurl%';
UPDATE `wp_redirection_404` SET url = REPLACE(url, 'oldsiteurl', 'newsiteurl') WHERE url LIKE 'oldsiteurl%'