Joel mentions some good alternatives to building a Debian package which you should seriously consider, since they are most likely a better fit. However, to answer your question directly, there are a few ways to go about it.
First, you could compile and package the software from scratch. This is a complicated process, and probably not what you want to do, but if so, check out the Debian New Maintainers' Guide.
Second, you could unpack the existing package, modify the source and build environment as needed, rebuild and repackage. This is fairly simple, though full of potential hazards. The steps are, generally,
build-essential package, which has the tools needed to build Debian packages.
Download the package source by running
apt-get source nginx, or whatever package name is appropriate. This will download and unpack the source package, including any patches, in a format ready to repackage. You may need to add or uncomment the
deb-src configuration lines in
/etc/apt/sources.list for the appropriate section of the repository.
Install the appropriate build dependencies with
apt-get build-dep nginx.
Make your modifications. Referring to the New Maintainers' Guide is helpful here, since the build will be automated, and may undo some of your changes. Be sure to increment the build version so that your package can be installed over the existing one.
Build the package with
dpkg-buildpackage -b. The
-b flag tells
dpkg that you don't want to regenerate the source package.
Install your package.
An easier approach is to use the
checkinstall program, which generates a Debian package by running an installation command and making a package that reproduces the changes that command made. This works for many software packages, and is fairly straightforward:
Download the source code and make your modifications as needed.
Build the project as you normally would (
make, for instance, but not
sudo checkinstall -D make install. You can modify this for a different installation command if necessary (
python setup.py install for Python projects, for instance).
Follow the interactive prompts to build the package. Knowledge of Debian packaging conventions is helpful to make a useful package; you'll have to copy dependencies from the existing package, for instance.
One final approach is to use Alien to convert an existing package (RPM, Slackware tgz, etc) to a
.deb package. I have not used this approach myself, and it requires an existing package that meets your needs in terms of compile-time configurations.
These options should all work for Debian or Ubuntu, but I've only tried them on Ubuntu.