Development
Serve Logs on Web Page Nginx

Documentation for PHP Log Viewer Setup with Nginx

Overview

This documentation describes how to set up a PHP script to view logs via a webpage and configure Nginx to serve the log viewing functionality securely. The setup includes Nginx configuration and a PHP script for displaying logs.

Nginx Configuration

Nginx Configuration File

Add the following configuration to your Nginx server block to serve a PHP script for viewing logs. This configuration assumes that you have PHP-FPM running and an .htpasswd file for basic authentication.

# Nginx server block for serving logs
location /logs {
    alias /var/www/project-path/public/logs.php;  # Path to the PHP script
    fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;  # Path to PHP-FPM socket
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $base/logs.php;  # PHP script to execute
    auth_basic "Restricted Access";  # Enable basic authentication
    auth_basic_user_file /etc/nginx/.htpasswd;  # Path to the htpasswd file
}

Basic Authentication

Create or modify the .htpasswd file to secure access to the log viewer. Use the htpasswd tool to create an encrypted password entry.

# Example htpasswd file entry
logs.php:$apr1$uawx2RaT$jmYIUljDsdalDepCh2DiE0

Place this file at /etc/nginx/.htpasswd.

PHP Script for Viewing Logs

PHP Script (logs.php)

Create a PHP script at /var/www/project-path/public/logs.php to display the log file content. Ensure that the PHP script has appropriate permissions to read the log file.

<?php
// logs.php
$logFile = '/var/www/my-proj/storage/logs/laravel.log'; // Path to your log file
 
// Check if the log file exists and is readable
if (file_exists($logFile) && is_readable($logFile)) {
    // Execute the tail command to get the last 300 lines
    $output = shell_exec('tail -n 300 ' . escapeshellarg($logFile));
    echo '<pre>' . htmlspecialchars($output) . '</pre>';
} else {
    echo 'Log file not found or not readable';
}
?>

Permissions

Ensure that the PHP script and log file have the correct permissions for reading and execution. The web server user should have access to these files.

# Set permissions for the PHP script
sudo chmod 644 /var/www/project-path/public/logs.php
 
# Set permissions for the log file
sudo chmod 644 /var/www/project-path/storage/logs/laravel.log
 
# Ensure the web server user owns the log file and PHP script
sudo chown www-data:www-data /var/www/project-path/public/logs.php
sudo chown www-data:www-data /var/www/project-path/storage/logs/laravel.log

Summary

This guide provides instructions for setting up a PHP script to view logs and configuring Nginx to serve the log viewer with basic authentication. By following these steps, you can securely view log files through a web interface.


🧙 AI Wizard - Instant Page Insights

Click the button below to analyze this page.
Get an AI-generated summary and key insights in seconds.
Powered by Perplexity AI!