Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
VGSources
Blog

How to Secure a New LAMP or LEMP Server on a VPS

Harden a fresh LAMP or LEMP VPS before launch with a staged Ubuntu checklist covering recovery, patching, SSH, UFW, PHP, databases, AppArmor, HTTPS, logging and restore tests.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Secure a new VPS before publishing its first application. Confirm provider-console recovery, patch the operating system, create and test a named administrator with SSH keys, restrict SSH and sudo, then use UFW and any provider firewall as an allowlist. Keep MySQL or MariaDB private, leave AppArmor enabled, automate and review security updates, and finish with HTTPS, protected secrets, logging, verified backups and a recovery test.

The controls are the same whether the web server is Apache in a LAMP stack or Nginx in a LEMP stack. The safest order is staged: preserve access first, change one boundary at a time, and verify from a separate session before closing the old route.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What to secure before the stack goes live

A VPS is an internet-reachable computer, not just a place to install PHP. A fresh image may have a public address, a privileged root account, listening services and unpatched packages. Hardening reduces the number of reachable services and limits what a compromised process can do.

Canonical’s Ubuntu Server guidance says to update regularly to stay protected from known vulnerabilities and to enforce least privilege. Those principles apply to the operating system, SSH, web server, PHP-FPM, database, files and recovery process.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Recovery is a prerequisite

Before editing SSH or firewall policy, sign in to the VPS provider’s web console, serial console or equivalent recovery channel. Confirm that it works while the server is healthy, record its credentials in your emergency procedure, and keep a second SSH session open while testing changes. Write down the current address and the SSH port you intend to retain. If a firewall rule locks you out, the recovery console is what lets you reverse it.

Stage 1: Patch Ubuntu and make updates observable

Use the distribution package manager before installing Apache, Nginx, PHP or a database. Refresh package indexes and install available upgrades, including security fixes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo apt update
sudo apt full-upgrade

Review proposed configuration-file changes rather than accepting an unfamiliar replacement blindly. Reboot when the installed kernel or another update requires it, then reconnect and confirm that the application prerequisites still work.

Enable unattended security upgrades

Ubuntu’s unattended-upgrades package can install updates from configured APT origins; the default policy includes Ubuntu security origins. Install and enable it according to the release’s package configuration, then inspect its logs regularly. Automatic installation is not a substitute for maintenance: failed jobs, held packages, kernel reboots, service restarts and application compatibility still need human review.

  • Check whether the last scheduled run completed successfully.
  • Track reboot requirements and schedule a controlled maintenance window.
  • Review package configuration changes after major upgrades.
  • Keep a rollback or recovery procedure for an update that prevents the application from starting.

Stage 2: Replace root administration with controlled SSH access

Create a named administrator

Create an individual account for each administrator instead of sharing root. Grant that account only the sudo rights needed for server operations. Test the account before disabling any existing route:

sudo adduser deployadmin
sudo usermod -aG sudo deployadmin

Use your organization’s actual username and access policy. On a production host, consider narrower sudo rules for operators who do not need unrestricted administrative commands; record who can approve and review those rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install and test an SSH key

Install the administrator’s public key in the new account’s SSH configuration, then open a separate terminal and log in with that key. Do not close the original session until the new login succeeds, sudo works as intended, and the account can reach the recovery procedure. A key test should include a fresh connection from the normal administration network, not merely a shell opened from an already-authenticated session.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Apply the SSH policy only after testing

Once key access is confirmed, disable direct root login and password authentication when the operational environment supports that policy. Make the change in the SSH daemon configuration, validate the configuration before restarting the service, and retain the second session while testing. If an automation system still requires passwords or a particular account, migrate that workflow first rather than locking out operations.

Restrict SSH at both layers when possible: the host firewall and the VPS provider’s security group. A source-network rule can limit SSH to a corporate VPN or fixed administration addresses, but keep an emergency route documented in case those addresses change.

Stage 3: Build a firewall allowlist

UFW is Ubuntu’s standard firewall frontend. The safe sequence is to add the SSH rule first, add web rules only when the site needs them, enable UFW, and inspect the result. A typical public web host needs SSH plus HTTP and HTTPS:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status numbered
sudo ufw status verbose

Port 22 is an example for a server that retains the conventional SSH port. If you deliberately use another port, allow that port instead and test it before enabling the firewall. HTTP (80) may be needed for initial certificate validation or an HTTP-to-HTTPS redirect; HTTPS (443) carries the public site.

Remove what the application does not need

Do not open database, cache, control-panel, mail or development ports merely because a package installed them. Remove obsolete UFW rules by number after checking the numbered status. Apply the same allowlist at the provider firewall or security group and keep the two policies consistent; allowing a port at one layer does not make it safe when the other layer is too broad.

Restrict administrative access by source where practical

For a private administration network, replace a global SSH allow rule with a rule limited to the approved source range. Rehearse the change from a second session and preserve the provider console route. Never assume an address-based rule is permanent: document how to update it when an office, VPN or ISP address changes.

Stage 4: Install only the required LAMP or LEMP components

Choose one web server, then install the PHP runtime and database engine the application actually requires. Apache forms the “A” in LAMP; Nginx forms the “E” in LEMP. Remove default sites, sample applications and unused modules after confirming the intended virtual host works. Leaving test content online can disclose version details or create an unintended execution path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Apache and Nginx decision points

Area Apache Nginx
Configuration model Virtual hosts and enabled modules; per-directory controls may be available where explicitly configured. Central server, HTTP and location blocks; configuration is validated and reloaded as a complete file set.
PHP integration May use a module or PHP-FPM; choose one deliberately and remove the unused path. Normally passes PHP requests to PHP-FPM over a socket or controlled network endpoint.
Static files and proxying Can serve files and proxy applications through configured modules. Strong static-file and reverse-proxy role, with explicit upstream and location rules.
Per-site isolation Use separate virtual-host identities, permissions and pools where the deployment requires them. Use separate server blocks, PHP-FPM pools and filesystem permissions where the deployment requires them.
Logs Review access and error logs for each virtual host and the global service. Review access and error logs for each server block and the global service.
Operational choice Prefer it when the team’s Apache module and virtual-host practices are well understood. Prefer it when the team’s Nginx, upstream and PHP-FPM practices are well understood.

Neither choice replaces host controls. Updates, least privilege, SSH policy, firewall rules, database isolation, AppArmor, TLS, monitoring and backups apply to both.

Stage 5: Protect the web process and PHP boundary

Separate the service identity

Run each application with a dedicated service account where the deployment model supports it. The web process should not own the whole document root. Make application files read-only to the web process except for specific upload, cache or generated-content directories that genuinely require writes.

  • Keep environment files, deployment keys and database credentials outside the document root.
  • Set file permissions so ordinary users and the web process cannot read private keys or another site’s secrets.
  • Disable directory listing unless a deliberate, authenticated file index is required.
  • Remove test files such as phpinfo() pages and sample configuration files.
  • Ensure the web process cannot traverse unrelated users’ home directories.

Review PHP-FPM pools and production settings

Give each application an appropriate PHP-FPM pool identity and restrict pool status endpoints to administrators or a private network. Review upload limits, execution timeouts and error display for production; detailed errors should go to protected logs rather than public responses. Confirm that the pool socket or network endpoint is writable and readable only by the intended web server and application accounts.

Stage 6: Harden MySQL or MariaDB

Keep the database private

For a single-host application, use a local socket or bind the database to localhost. If the database is on another private server, bind it to the required private interface and restrict the provider and host firewalls to the application network. Do not expose a database service to the whole internet for routine administration; use local access, a private network or an SSH tunnel instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Remove defaults and narrow privileges

Run the database vendor’s hardening procedure. Remove anonymous users, test databases and unused accounts. Create an application-specific database user and grant only the schema privileges the application needs; do not use the database superuser in the application configuration. Use separate credentials for migrations, operations and the runtime when the application supports that separation.

Encrypt traffic that leaves the host

If database traffic crosses a network boundary, configure encrypted connections and verify certificate validation rather than relying solely on network isolation. Back up the database independently from site files and perform a restore test on a disposable or isolated environment.

Stage 7: Keep AppArmor enabled

AppArmor is Ubuntu’s per-program mandatory access-control system. It limits the files and capabilities a confined application can use and is installed and loaded by default on Ubuntu. Check its state after installing or changing Apache, Nginx, PHP or database packages:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
sudo aa-status

Do not disable AppArmor to hide a denial without investigating it. If a legitimate application needs an additional path or capability, place local profile adjustments in the documented local-override locations. Test a new custom profile in complain mode, review denials, then enforce it after confirming that normal requests, scheduled jobs and backups still work.

Stage 8: Configure HTTPS and protect certificate keys

Use an ACME-capable certificate workflow or another trusted issuance process, monitor renewal, and perform a renewal dry run before the certificate approaches expiry. Configure the web server’s TLS virtual host, redirect ordinary HTTP traffic to HTTPS after issuance, and leave HTTP available only for the validation and redirect behavior required by the deployment.

Nginx TLS example

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
}

The certificate is public; the private key is not. Restrict the key file to the account that must read it, protect the certificate directory from ordinary users, and check permissions after every renewal. For Apache, apply the equivalent certificate, key-permission and modern-protocol policy in the SSL virtual host.

Stage 9: Monitor, log and prepare for recovery

Review the right logs

Monitor SSH authentication, the web server, PHP-FPM and the database. Look for repeated failures, unexpected administrative actions, application errors and unusual request patterns. Send important logs to an off-host system when possible so an attacker who gains local access cannot erase every record.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use rate limiting as a supplement

A rate-limiting or intrusion-prevention tool can react to repeated authentication failures, but it does not replace SSH keys, least privilege or a narrow firewall. Tune thresholds so a noisy client cannot block legitimate administrators, and make sure the tool’s own rules do not conflict with the provider firewall.

Verify encrypted, versioned backups

Keep encrypted, versioned copies of both database backups and application files. Test restoration, not merely backup creation: restore the database, site files, configuration and certificates into an isolated environment and confirm that the application starts. A backup that has never been restored is unverified.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Stage 10: Run a pre-launch security check

Complete these checks from a new administration session and from an external network where appropriate:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
  • SSH key login works for the named administrator.
  • Root login and password authentication follow the policy you documented.
  • UFW and the provider firewall expose only the required SSH, HTTP and HTTPS paths.
  • ss -tulpn shows no unexpected listening service.
  • The database is reachable only locally or through the approved private network.
  • aa-status shows the expected AppArmor profiles loaded and enforcing.
  • HTTP redirects to HTTPS, the certificate presents correctly, and renewal succeeds in a staging or dry-run procedure.
  • The application cannot read private keys, environment files or another site’s files.
  • Database and file backups restore successfully.
  • Provider-console credentials and the documented recovery procedure are available to the on-call administrator.

Common failure modes and safe fixes

SSH access disappears after enabling UFW

Use the provider or serial console, inspect numbered UFW rules, add the correct SSH port or source range, and test from a second terminal before ending the console session. Do not repeatedly reboot without correcting the rule.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Automatic updates leave a reboot pending

Confirm which package requested the reboot, schedule maintenance, reboot through the provider’s normal procedure, and verify SSH, the web service, PHP-FPM, the database and scheduled jobs afterward.

PHP uploads fail after permissions are tightened

Do not make the entire web root writable. Create one purpose-specific upload or cache directory, assign it to the application identity, constrain its allowed file types and execution behavior, and keep the rest of the code read-only.

AppArmor blocks a legitimate operation

Read the denial, identify the exact path or capability needed, add a local override rather than editing the vendor profile, test in complain mode, and enforce only after normal traffic and maintenance jobs succeed.

Certificate renewal fails

Check that the validation path is reachable on the required HTTP or HTTPS port, that the web server reloads its configuration, that the private key directory remains readable by the renewal process, and that the dry-run procedure is part of regular maintenance rather than a one-time setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What changes between LAMP and LEMP?

The web-server configuration and PHP handoff differ, so the paths for virtual hosts, logs, service reloads and PHP-FPM pools must follow the selected server’s conventions. Apache may use a module or PHP-FPM; Nginx normally delegates dynamic PHP requests to PHP-FPM. Static-file handling, reverse-proxy rules and per-site isolation also differ.

The host-level security baseline does not change: patching, named key-based administration, least-privilege sudo, an allowlist firewall, private database access, AppArmor, TLS, log review, backup restoration and a tested recovery route are required for either stack. Choose the server your team can operate and troubleshoot correctly, then document its exact configuration and reload procedure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.