Nginx + Node. js build an image server
Image Upload requests are processed by Node, and image access requests are processed by Nginx.
1. Nginx Configuration
# User nobody;
Worker_processes 1;
# Error_log logs/error. log;
# Error_log logs/error. log notice;
# Error_log logs/error. log info;
# Pid logs/nginx. pid;
Events {
Worker_connections 1024;
}
Http {
Include mime. types;
Default_type application/octet-stream;
# Log_format main '$ remote_addr-$ remote_user [$ time_local] "$ request "'
# '$ Status $ body_bytes_sent "$ http_referer "'
# '"$ Http_user_agent" "$ http_x_forwarded_for "';
# Access_log logs/access. log main;
Sendfile on;
Tcp_nopush on;
Sendfile_max_chunk 256 K;
# Keepalive_timeout 0;
Keepalive_timeout 65;
# Gzip on;
Upstream localhost {
Server localhost: 3000; # node server
}
Server {
Listen 80;
Server_name localhost;
# Enable the index function
Autoindex on;
# Disable the exact size of the computing File
Autoindex_exact_size off;
# Charset koi8-r;
# Access_log logs/host. access. log main;
# Upload operations are processed by the node Server
Location /{
Proxy_pass http: // localhost;
Index index.html;
}
# Ing image access url
Location/image /{
Expires 30d; # Cache Time
Root E:/Study/nginx/nginx-1.7.6/files;
}
# Error_page 404/404 .html;
# Redirect server error pages to the static page/50x.html
#
Error_page 500 502 503 x.html;
Location =/50x.html {
Root html;
}
# Proxy the PHP scripts to Apache listening on 127.0.0.1: 80
#
# Location ~ \. Php $ {
# Proxy_pass http: // 127.0.0.1;
#}
# Pass the PHP scripts to FastCGI server listening on Fig: 9000
#
# Location ~ \. Php $ {
# Root html;
# Fastcgi_pass 127.0.0.1: 9000;
# Fastcgi_index index. php;
# Fastcgi_param SCRIPT_FILENAME/scripts $ fastcgi_script_name;
# Include fastcgi_params;
#}
# Deny access to. htaccess files, if Apache's document root
# Concurs with nginx's one
#
# Location ~ /\. Ht {
# Deny all;
#}
}
# Another virtual host using mix of IP-, name-, and port-based configuration
#
# Server {
# Listen 8000;
# Listen somename: 8080;
# Server_name somename alias another. alias;
# Location /{
# Root html;
# Index index.html index.htm;
#}
#}
# HTTPS server
#
# Server {
# Listen 443 ssl;
# Server_name localhost;
# Ssl_certificate cert. pem;
# Ssl_certificate_key cert. key;
# Ssl_session_cache shared: SSL: 1 m;
# Ssl_session_timeout 5 m;
# Ssl_ciphers HIGH :! ANULL :! MD5;
# Ssl_prefer_server_ciphers on;
# Location /{
# Root html;
# Index index.html index.htm;
#}
#}
}
2. nodejs project Architecture
1) Project Structure
2) bin/www is the Startup Script
#! /Usr/bin/env node
Var debug = require ('debug') ('file-Server ');
Var app = require ('../app ');
App. set ('Port', process. env. port | 3000 );
Var server = app. listen (app. get ('Port'), function (){
Console. log ('express server listening on port' + server. address (). port );
Debug ('express server listening on port' + server. address (). port );
});
3) config/setting. json is a constant in the program configured in json format.
{
"Image_url": "http: // localhost/image ",
& Quot; image_dir & quot;: & quot; E:/Study/nginx/nginx-1.7.6/files/image & quot ",
& Quot; tmp_dir & quot;: & quot; E:/Study/nginx/nginx-1.7.6/tmp & quot"
}
4) controller/file-ctrl.js is the processing code for File Upload
Var fs = require ('fs ');
Var path = require ('path ');
Var formidable = require ('formidable ');
Var util = require ('til ');
Var fs = require ('fs ');
Var path = require ('path ');
Var setting = require ('../config/setting. json ');
/**
* Upload
*/
Exports. upload = function (req, res ){
Var form = new formidable. IncomingForm ();
Form. encoding = 'utf-8 ';
// If you need temporary files to keep the original file extension, set it to true.
Form. keepExtensions = false;
// File size limit, 2 MB by default
Form. maxFieldsSize = 2*1024*1024;
// Image storage directory
Var imageDir = setting. image_dir;
// Upload a temporary directory
Var tmpDir = setting. tmp_dir;
Form. uploadDir = tmpDir; // The directory must already exist.
/**
* Other attributes in the fields form
* Files file set
*/
Form. parse (req, function (err, fields, files ){
// Complete image path
Var imagePath = path. resolve (imageDir, files. file. name );
// Move the images in the temporary directory to the image storage directory
Fs. rename (files. file. path, imagePath, function (err ){
If (err ){
Res. json ({'success': false, 'msg ': err });
} Else {
Var image_url = setting. image_url + '/' + files. file. name;
Res. json ({'success': true, 'msg ': 'upload successful! ', 'Image _ url': image_url });
// Res. json ({'success': true, 'msg ':' uploaded successfully! ', 'Image _ url': image_url, 'fields': util. inspect ({fields: fields, files: files })});
}
});
});
}
/**
* Download
*/
Exports. download = function (req, res ){
Var filename = req. params. filename;
Var dir = setting. file_dir;
Var file_path = path. resolve (dir, filename );
Fs. exists (file_path, function (exists ){
If (! Exists ){
Res. json ({'success': false, 'msg ':' the file does not exist! '});
} Else {
Res. download (file_path, function (err ){
If (err ){
Res. json ({'success': false, 'msg ': err });
}
});
}
});
}
5) routes/route. js is the route control for the entire project.
Var express = require ('express ');
Var router = express. Router ();
Var file_ctrl = require ('../controller/file-ctrl ')
/** Upload a file */
Router. post ('/upload', file_ctrl.upload );
Module. exports = router;
6) app. js is the global configuration of the project.
Var express = require ('express ');
Var path = require ('path ');
Var favicon = require ('static-favicon ');
Var logger = require ('Morgan ');
Var cookieParser = require ('cookie-parser ');
Var bodyParser = require ('body-parser ');
Var routes = require ('./routes/route ');
Var app = express ();
// View engine setup
App. set ('view', path. join (_ dirname, 'view '));
App. set ('view engine ', 'jade ');
App. use (favicon ());
App. use (logger ('dev '));
App. use (bodyParser. json ());
App. use (bodyParser. urlencoded ());
App. use (cookieParser ());
App. use (express. static (path. join (_ dirname, 'public ')));
App. use ('/', routes );
/// Catch 404 and forward to error handler
App. use (function (req, res, next ){
Var err = new Error ('not Found ');
Err. status = 404;
Next (err );
});
/// Error handlers
// Development error handler
// Will print stacktrace
If (app. get ('env') = 'development '){
App. use (function (err, req, res, next ){
Res. status (err. status | 500 );
Res. render ('error ',{
Message: err. message,
Error: err
});
});
}
// Production error handler
// No stacktraces leaked to user
App. use (function (err, req, res, next ){
Res. status (err. status | 500 );
Res. render ('error ',{
Message: err. message,
Error :{}
});
});
Module. exports = app;
6) package. json is dependent on package management.
{
"Name": "file-server ",
"Version": "0.0.1 ",
"Private": true,
"Scripts ":{
"Start": "node./bin/www"
},
"Dependencies ":{
"Express ":"~ 4.2.0 ",
"Static-favicon ":"~ 1.0.0 ",
"Morgan ":"~ 1.0.0 ",
"Cookie-parser ":"~ 1.0.1 ",
"Body-parser ":"~ 1.0.0 ",
"Debug ":"~ 0.7.4 ",
"Jade ":"~ 1.3.0 ",
"Formidable ":"*"
}
}
The project uses the expressjs framework.
3. Simply write an html upload page
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> upload </title>
<Meta http-equiv = "pragma" content = "no-cache">
<Meta http-equiv = "cache-control" content = "no-cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "This is my page">
<! --
<Link rel = "stylesheet" type = "text/css" href = "styles.css">
-->
</Head>
<Body>
<Form action = "http: // localhost/upload" method = "post" enctype = "multipart/form-data">
<Input type = "file" name = "file">
<P>
<Input type = "submit" value = "Upload">
</Form>
</Body>
</Html>
4. Start the node server and Nginx Server
Go to the project root directory and run node bin \ www or npm start (this is the script command "scripts" configured in package. json ")
5. Test
1) upload images
2) Upload successful
3) Access image_url to view the image.
For more Nginx tutorials, see the following:
Deployment of Nginx + MySQL + PHP in CentOS 6.2
Build a WEB server using Nginx
Build a Web server based on Linux6.3 + Nginx1.2 + PHP5 + MySQL5.5
Performance Tuning for Nginx in CentOS 6.3
Configure Nginx to load the ngx_pagespeed module in CentOS 6.3
Install and configure Nginx + Pcre + php-fpm in CentOS 6.4
Nginx installation and configuration instructions
Nginx log filtering using ngx_log_if does not record specific logs
Nginx details: click here
Nginx: click here
This article permanently updates the link address: