Skip to content

Instantly share code, notes, and snippets.

@vividsnow
Created September 28, 2021 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vividsnow/df631af2a975eed07f2f2dbb2915f5ef to your computer and use it in GitHub Desktop.
Save vividsnow/df631af2a975eed07f2f2dbb2915f5ef to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict; use utf8; use warnings; use autodie ':all';
use File::Temp qw'tempfile tempdir';
use Getopt::Std 'getopts';
use Cwd 'cwd';
use File::Spec::Functions qw'catfile rel2abs';
my %o = (qw'l 0:4321 -d', cwd);
getopts 'l:d:u:p:h', \%o;
print <<\txt and exit 0 if $o{h};
usage:
share-via-nginx [-d path_to_dir] [-l host:port] [-u name -p password]
txt
$0 = join ' ', $0, map { $o{$_} ? "-$_ ".$o{$_} : () } qw'l d u';
my $tmp = tempdir(uc'cleanup', 1);
my $dir = rel2abs $o{d};
printf "sharing %s on %s, nginx work dir: %s\n", $dir, $o{l}, $tmp;
my $auth = '';
if ($o{u}) {
open my $pfh, '>', my $pass_file = catfile $tmp, 'htpasswd';
printf $pfh "%s:%s:user\n", $o{u}, crypt $o{p}//'', 'whatever';
$auth = q(auth_basic 🧐; auth_basic_user_file htpasswd;);
}
open my $cfh, '>:utf8', my $conf_file = catfile($tmp, 'nginx.conf');
print $cfh <<\txt =~ s/~listen~/$o{l}/re =~ s/~dir~/$dir/r =~ s/~auth~/$auth/r;
error_log stderr error;
daemon off;
master_process off;
pid nginx.pid;
events {}
http {
access_log access.log;
include /etc/nginx/mime.types;
types {
video/x-matroska mkv;
text/csv csv;
application/epub+zip epub;
}
gzip on;
gzip_types text/plain text/csv application/vnd.ms-excel;
charset utf-8;
sendfile on;
tcp_nopush on;
aio on;
server {
listen '~listen~' default_server;
location / {
root '~dir~';
autoindex on;
autoindex_exact_size off;
autoindex_format html;
~auth~
}
location /favicon.ico {
access_log off;
return 204;
}
}
}
txt
close $cfh;
exec qw'/usr/sbin/nginx -p', $tmp, '-e', catfile($tmp, 'err.log'), '-c', $conf_file
unless my $nginx_pid = fork;
unless (my $tail_pid = fork) {
open STDERR, '>', '/dev/null';
exec qw'/usr/bin/tail -F', catfile $tmp, 'access.log';
}
$SIG{INT} = 'IGNORE';
1 while wait > -1;
print "bye!\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment