October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

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

A practical, staged guide to securing a new LAMP or LEMP server on an Ubuntu VPS before it goes live, from recovery access and SSH keys to firewalls, PHP, databases, TLS and restore testing.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Secure the VPS before you publish the application. Confirm a provider or serial-console recovery path, patch the operating system, create and test a named administrator with SSH keys, enforce least-privilege sudo, allow only required ports, keep the database private, verify AppArmor, configure HTTPS, and test both backups and recovery. The same host controls apply whether you choose Apache (LAMP) or Nginx (LEMP).

What a secure first deployment should achieve

A fresh VPS is an internet-facing computer, not an application appliance. Before the first public request reaches it, you should be able to answer five questions:

As an Amazon Associate I earn from qualifying purchases.

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.
  • Can you recover access if an SSH or firewall change locks you out?
  • Which named account administers the host, and is direct root or password login disabled?
  • Which ports are intentionally reachable from the internet?
  • Can the web process, PHP runtime and database access only what the application needs?
  • Can you restore the site and database after a destructive failure?

Hardening is a sequence rather than a single package. Perform changes in an order that preserves access, and keep a second administrative session open while testing authentication and firewall changes.

1. Preserve a recovery path before changing anything

Confirm out-of-band access

Sign in to the VPS provider’s web console, serial console or equivalent recovery environment before editing SSH or firewall policy. Verify that it can open a shell or provide a documented reset procedure. Store the console credentials in your normal password manager and record the server’s current public IP address.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Keep a second session

Do not close your working SSH session while testing a new account, key or firewall rule. Open a separate terminal and log in with the new credentials before applying changes that could disable the original connection. If the second login fails, use the first session or recovery console to correct the configuration.

Record the administration port

Note the SSH port you intend to retain. A standard Ubuntu installation normally uses TCP 22; a custom port must be allowed explicitly in both the host firewall and any provider security group. Changing a port is not a substitute for key authentication and least privilege.

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

2. Patch the base operating system

Apply updates before installing the stack

Refresh package indexes and install current upgrades before adding Apache, Nginx, PHP or a database:

sudo apt update
sudo apt full-upgrade -y

Reboot when the package manager indicates that a kernel or other system component requires it, then reconnect and confirm the expected hostname, IP address and service state.

Enable unattended security upgrades

Ubuntu’s unattended-upgrades package can install security updates from configured APT origins; the default policy includes Ubuntu security origins. Install and configure it, then inspect the policy rather than assuming every repository is covered:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

Automatic updates reduce the window in which known vulnerabilities remain unpatched, but they do not remove maintenance work. Review update logs, investigate failed jobs, watch for package-configuration conflicts, and schedule reboots when a kernel update requires one. Test application compatibility after major library or PHP updates.

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

3. Create controlled administration with SSH keys

Create a named administrator

Use a personal, named account instead of sharing root credentials. On Ubuntu, create the account and grant the sudo group only if that user genuinely needs full administrative operations:

sudo adduser adminname
sudo usermod -aG sudo adminname

For operators who need only a narrow task, use a specific sudoers rule rather than unrestricted sudo. Edit policy with sudo visudo so syntax errors are rejected before they can break administration.

Install and test the public key

Copy the administrator’s public key to the account, or add it to /home/adminname/.ssh/authorized_keys with ownership and permissions that prevent other users from modifying it. Test a new connection in a separate terminal:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
ssh adminname@server-ip

Confirm that the key works after a fresh connection, not just in an agent session that may be masking a missing key. Test sudo -v and one harmless administrative command.

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

Disable weaker SSH paths after verification

Once key login and the recovery route are confirmed, edit the SSH server configuration (normally /etc/ssh/sshd_config) to follow your operational policy:

PermitRootLogin no
PasswordAuthentication no

Check the configuration before reloading and use the service’s reload command for your Ubuntu release. Keep the existing session open while you test a new key-based login. If an environment requires temporary password access, restrict it by source network and set a removal date rather than leaving it permanently enabled.

4. Configure UFW and provider firewalls as an allowlist

Add SSH before enabling UFW

UFW is Ubuntu’s standard firewall frontend. Add the SSH rule that matches the port you recorded, then add web ports only when the server will actually serve public HTTP or HTTPS:

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

If SSH uses another port, replace 22 with that port. For administration from a fixed office or VPN range, narrow the rule by source address instead of allowing the entire internet.

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

Inspect and remove unnecessary rules

sudo ufw status numbered
sudo ufw status verbose

Delete rules by their displayed number after checking that the replacement SSH rule works. Leave no rule for a service that is not required by the deployment. A public website normally needs TCP 80 and 443 plus the administration port; it does not normally need a public database, cache, mail, or development port.

Keep provider and host policy consistent

If the VPS platform supplies a security group or network ACL, apply the same allowlist there. A port blocked upstream will be unreachable even when UFW permits it; a port allowed upstream remains exposed if UFW permits it later. Review both layers after every service installation.

5. Install only the required LAMP or LEMP components

Choose the web-server model deliberately

Area LAMP (Apache) LEMP (Nginx)
Web server Apache HTTP Server; configuration is commonly organized around virtual hosts and directory/context rules. Nginx; configuration uses server blocks and is often selected for static-file delivery and reverse-proxy workloads.
PHP integration May use an Apache PHP module or PHP-FPM, depending on the distribution and deployment. Normally passes PHP requests to PHP-FPM over a Unix socket or TCP endpoint.
Static files and proxying Can serve static content and proxy applications through modules. Efficient static delivery and explicit reverse-proxy configuration are central to its model.
Per-site isolation Use separate virtual hosts, service identities and filesystem permissions; do not rely on a shared writable document root. Use separate server blocks, PHP-FPM pools where appropriate and restrictive filesystem permissions.
Operational choice Often familiar to teams using .htaccess-style workflows and Apache modules. Often familiar to teams preferring centralized configuration and a reverse-proxy front end.

These differences change configuration syntax and logging paths, not the security baseline. Updates, least privilege, SSH keys, an allowlist firewall, private database binding, AppArmor, TLS, monitoring and tested backups are required for either stack.

Remove defaults after confirming the intended site

Install only the web server, PHP packages, PHP-FPM where used, database service and modules the application needs. Before deleting a distribution default site, confirm that the intended virtual host or server block responds correctly. Remove sample applications, test pages and unused modules after documenting any dependency they provided.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

6. Protect the application and PHP boundary

Use a dedicated service identity

Run each application with an appropriate service account and least-privilege ownership. The web process should not own the entire operating system, another site’s files, users’ home directories or private keys. Make the document root non-writable by the web process unless a narrowly scoped upload, cache or generated-content directory requires write access.

Keep secrets out of the document root

Place database passwords, API tokens and environment files outside the directory that Apache or Nginx serves. Restrict them to the application identity and administrators, and check that deployment archives, version-control directories and editor backups are not web-accessible.

Harden PHP and PHP-FPM

Remove test pages such as phpinfo() before launch. Disable directory listing. For PHP-FPM, select a pool identity that matches the application, expose status endpoints only to an authenticated local monitor, and review upload limits, execution settings and error display for production. Public error output can disclose paths, configuration and secrets; send diagnostic detail to protected logs instead.

After permission changes, test that the web process cannot read an unrelated user’s home directory, SSH private key, another site’s environment file or the server’s package and credential stores.

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

7. Harden MySQL or MariaDB

Run the vendor hardening procedure

Use the database package’s supported hardening workflow to remove anonymous accounts, test databases and other default access paths. Set a strong administrative credential or use the distribution’s local-socket authentication model where appropriate.

Create an application-specific account

Do not let the application connect as the database administrator. Create a user for the application and grant only the schema operations it needs. Separate migration or maintenance credentials from the runtime account when the deployment process permits it.

Keep the database off the public internet

Bind MySQL or MariaDB to localhost or a private interface. Prefer a local Unix socket, private network, or an SSH tunnel for administration. Do not open TCP 3306 to the whole internet for routine management. If traffic must leave the host, require encrypted database connections and restrict source addresses at both the provider firewall and UFW.

Back up and restore separately

Back up database contents independently from application files, protect the backup copies with encryption and access controls, and perform a real restore test. A successful backup job is not evidence that the data can be recovered until a restore has completed and the application can read the restored database.

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

8. Keep AppArmor enabled

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

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
sudo aa-status

Unexpected denials may indicate a real attack or an application that needs a documented permission. Put local profile adjustments in the distribution’s documented local-override locations rather than editing the vendor profile directly. Test a new custom profile in complain mode, review the resulting logs, and enforce it only after legitimate application behavior works.

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

9. Configure HTTPS and protect certificate keys

Use modern TLS settings

Obtain a certificate through an ACME-capable workflow or another managed certificate process, install it in the correct virtual host or server block, and restrict the private-key file to the accounts that must read it. The certificate is public information; the private key is a secret.

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

An Nginx HTTPS server block can follow this pattern, adapted to your certificate paths and hostname:

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;
}

Apply the equivalent certificate, key-permission and modern-protocol policy in an Apache SSL virtual host. Redirect normal HTTP requests to HTTPS after issuance. Keep port 80 reachable only when the site needs HTTP-to-HTTPS redirects or certificate validation; do not treat it as an alternate unencrypted application endpoint.

Test renewal before expiry

Monitor certificate expiry and run the certificate client’s staging or dry-run renewal procedure. Confirm that renewal can reload the web server without replacing the private key with incorrect ownership or permissions.

10. Add detection, logging and rate controls

Review the right logs

Establish a routine for SSH authentication logs, Apache or Nginx access and error logs, PHP-FPM logs, database logs, UFW events and AppArmor denials. Know the log locations for your distribution and service packages, and configure rotation so a busy site cannot fill the root filesystem.

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

Send important records off-host

Forward security-relevant logs to a separate system when possible. An attacker who gains control of the VPS should not be able to erase the only record of the activity. Protect the receiving system with its own authentication, retention and access policy.

Use rate limiting as a supplement

A rate-limiting or intrusion-prevention service can react to repeated authentication failures, but it does not replace key-based SSH, a restricted firewall and least-privilege accounts. Tune thresholds so legitimate administrators are not locked out, and ensure your recovery console remains available.

11. Backups and recovery are part of hardening

Define what must be restored

  • Database dumps or snapshots with encryption and retention controls.
  • Application files, uploaded media and deployment configuration.
  • Web-server, PHP-FPM and firewall configuration needed to rebuild the service.
  • Certificate renewal configuration, while keeping private keys protected.
  • A current record of DNS, provider firewall rules and administrative access.

Perform a restore test

Restore the database and site files to an isolated VPS or recovery environment. Verify file ownership, permissions, database connectivity, HTTPS configuration and application behavior. Record the time required and the commands used so another administrator can repeat the procedure.

12. Validate the server before launch

Run these checks from a new administrative session and, where possible, from an external network:

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.
  • SSH key login works for the named administrator.
  • Root login and password authentication follow the policy you set.
  • UFW and the provider firewall expose only the administration port and required web ports.
  • ss -tulpn shows no unexpected listening service.
  • MySQL or MariaDB is not publicly reachable and uses the intended local or private bind address.
  • aa-status shows the expected profiles loaded and enforcing.
  • HTTP redirects to HTTPS, the certificate matches the hostname, and renewal succeeds in a staging or dry-run procedure.
  • The application cannot read private keys, environment files, another site’s files or unrelated home directories.
  • Backups restore successfully, and the provider recovery console credentials are available.

Do not publish until an unexpected listener, broad filesystem permission or failed restore has been explained and corrected.

Common failure modes and safe fixes

UFW locked out SSH

Use the provider console, add the correct SSH port rule, and verify it from a second session before closing the console or original connection. If a provider security group blocks the port, correct that layer as well.

The new key is rejected

Check that the public key is complete, the account owns its .ssh directory and authorized_keys, and permissions do not allow group or world writes. Inspect SSH authentication logs from the existing session or console before re-enabling password access.

PHP returns a blank page or 502 error

Confirm that PHP-FPM is running, that the web server points to the correct socket, and that the pool identity can read the application files. Review PHP-FPM and web-server error logs. Do not make the entire document root world-writable as a quick fix.

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

AppArmor blocks a legitimate request

Identify the denied path and operation in the logs, verify that the application truly needs it, and add the smallest local profile adjustment. Test in complain mode before enforcing the revised profile.

Automatic updates cause a service change

Review unattended-upgrade logs, package configuration prompts and reboot requirements. Test the application against the updated runtime, then schedule a controlled restart rather than disabling security updates wholesale.

Certificate renewal fails

Check DNS, port 80 validation access, file permissions and the certificate client’s logs. Run a staging or dry-run renewal, then confirm the web server reloads with the renewed certificate and private key.

Ongoing maintenance after launch

  • Review unattended-upgrade results and reboot requirements on a defined schedule.
  • Remove unused packages, modules, accounts and firewall rules whenever the application changes.
  • Audit listening sockets with ss -tulpn after installing a new service.
  • Review SSH, web, PHP-FPM, database, UFW and AppArmor logs for anomalies.
  • Check certificate expiry and renewal status before the certificate’s final renewal window.
  • Run backup restoration tests at an interval appropriate to the site’s recovery objectives.
  • Re-test provider-console access and update the recovery runbook after personnel or network changes.

A secure LAMP or LEMP VPS is therefore an operating practice: recoverable access, current packages, named administrators, a narrow network boundary, isolated application and database permissions, enforced mandatory access control, encrypted transport, useful logs and proven restoration. Apache and Nginx change the configuration details, but neither changes that baseline.

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

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 *

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.